首页 > 解决方案 > 如何在arduino中将字符串拆分为单词?

问题描述

我在arduino中有一个字符串

String name="apple orange banana";

是否可以将每个项目存储在数组中 arr

以便

arr[0]="apple" 
arr[1]="orange" ......etc

如果不将它们存储在单个变量中?

标签: arduino

解决方案


如何使用 Arduino 中的特定分隔符拆分字符串?我相信这会对你有所帮助,你可以做一个 while 循环,如:

int x;
String words[3];
while(getValue(name, ' ', x) != NULL){
     words[x] = getValue(name, ' ', x);
}

使用此功能:

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

推荐阅读