我有一个String变量,并且我想提取由分隔的三个子字符串;到三个字符串变量。
String application_command = "{10,12; 4,5; 2}";
我不能使用子字符串方法,因为此字符串也可以类似于以下任何一种或类似的模式。
String application_command = "{10,12,13,9,1; 4,5; 2}"
String application_command = "{7; 1,2,14; 1}"
这些模式中唯一的共同点是三个部分由;分隔。
非常感谢任何见解。
谢谢
最佳答案
我认为您需要具有自定义分隔符的split-string-into-string-array
函数。
网络上和堆栈溢出中已经有多个来源(例如Split String into String array)。
// https://stackoverflow.com/questions/9072320/split-string-into-string-array
String getValue(String data, char separator, int index)
{
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length()-1;
for(int i=0; i<=maxIndex && found<=index; i++){
if(data.charAt(i)==separator || i==maxIndex){
found++;
strIndex[0] = strIndex[1]+1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}
您可以按以下方式使用此函数(以“;”作为分隔符):
String part01 = getValue(application_command,';',0);
String part02 = getValue(application_command,';',1);
String part03 = getValue(application_command,';',2);
编辑:纠正单引号并在示例中添加分号。
关于arduino - 如何在Arduino中使用特定的分隔符分割字符串?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29671455/