提问者:小点点

在分隔符之间将字符串拆分为单个变量


我试图找到一种更优雅/内存占用更少的方法,通过分隔符拆分一个char数组。

字符数组:“192.168.178\nWifiSid\nWifiPassword\n123”

我愚蠢的分裂方式:

void convertPayload() 
{
qrData = (char*)mypayload;

String ssidtmp = qrData;
ssidtmp.remove(qrData.indexOf("\n"), qrData.length()+1);
EEPROM.writeString(ssidAddr,ssidtmp);
EEPROM.commit();

String passtmp = qrData;
passtmp.remove(0, passtmp.indexOf("\n")+1);
passtmp.remove(passtmp.indexOf("\n"),passtmp.length()+1);

EEPROM.writeString(passAddr, passtmp);
EEPROM.commit();

String modulenrtmp = qrData;
modulenrtmp.remove(0, modulenrtmp.indexOf("\n") + 1);
modulenrtmp.remove(0, modulenrtmp.indexOf("\n") + 1);
modulenrtmp.remove(modulenrtmp.indexOf("\n") , modulenrtmp.length());
int modNRINT = modulenrtmp.toInt();

EEPROM.write(moduleNraddress, modNRINT);
EEPROM.commit();

String ftptmp = qrData;
ftptmp.remove(0, ftptmp.indexOf("\n") + 1);
ftptmp.remove(0, ftptmp.indexOf("\n") + 1);
ftptmp.remove(0, ftptmp.indexOf("\n") + 1);
ftptmp.remove(ftptmp.indexOf("\n") , ftptmp.length());

EEPROM.writeString(ftpAddr, ftptmp);
EEPROM.commit();

EEPROM.writeBool(configModeAddr, true);
EEPROM.commit();

//indicate QR succesfully read
blinkBurst(2, 300);

ESP.restart();
}

正如您所看到的,我正在创建不必要的字符串。 正确的做法是什么?

为您抽出时间干杯,谢谢!


共1个答案

匿名用户

如果可以编辑MyPayLoad,则可以使用std::strTok

void convertPayload() {

String ssidtmp = std::strtok(mypayload, "\n");
EEPROM.writeString(ssidAddr,ssidtmp);
EEPROM.commit();

String passtmp = std::strtok(nullptr, "\n");
EEPROM.writeString(passAddr, passtmp);
EEPROM.commit();

String modulenrtmp = std::strtok(nullptr, "\n");
int modNRINT = modulenrtmp.toInt();
EEPROM.write(moduleNraddress, modNRINT);
EEPROM.commit();

String ftptmp =  = std::strtok(nullptr, "\n");
EEPROM.writeString(ftpAddr, ftptmp);
EEPROM.commit();

EEPROM.writeBool(configModeAddr, true);
EEPROM.commit();

//indicate QR succesfully read
blinkBurst(2, 300);

ESP.restart();
}

相关问题