且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将字符串拆分为字符串数组

更新时间:2022-05-22 16:35:07

这是一个老问题,但我已经创建了一些可能有帮助的代码:

This is an old question, but i have created some piece of code that may help:

 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]) : "";
}

此函数返回由给定索引处的预定义字符分隔的单个字符串.例如:

This function returns a single string separated by a predefined character at a given index. For example:

String split = "hi this is a split test";
String word3 = getValue(split, ' ', 2);
Serial.println(word3);

应该打印'is'.您也可以尝试使用索引 0 返回 'hi' 或安全地尝试使用索引 5 返回 'test'.

Should print 'is'. You also can try with index 0 returning 'hi' or safely trying index 5 returning 'test'.

希望对您有所帮助!