首页 > 解决方案 > 将字符串拆分为分隔符之间的单个变量

问题描述

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

字符数组:“192.168.178\nWiFiSSID\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();
}

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

干杯并感谢您的宝贵时间!

标签: c++stringsplit

解决方案


如果您可以编辑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();
}

推荐阅读