【问题标题】:Convert a String to an integer array将字符串转换为整数数组
【发布时间】:2018-01-23 19:57:22
【问题描述】:

我有一个 ESP8266 (Arduino),它接收 20 个数字的字符串(根据 Arduino String 类库),范围从 0 到 200,逗号分隔。

我想解析这些值并将其放入一个整数数组中(例如 int IntArray[21];。这就是字符串的样子:

dataFromClient = "1,2,1,0,1,1,0,1,0,25,125,0,175,100,0,25,175,0,50,125";

在过去的 2 周里,我已经尝试了无数次,但我不断陷入“字符串”地狱!任何帮助将不胜感激。

【问题讨论】:

  • 克里斯,非常感谢!!这完美地工作。我正在尝试使用 char 字符串、strtok 等。再次感谢!

标签: arrays string arduino


【解决方案1】:

你应该提供更多关于你迄今为止尝试过的细节。

由于您使用的是 Arduino 库,因此您可以使用字符串类的 toInt() 成员函数。

unsigned int data_num = 0;
int data[21];
// loop as long as a comma is found in the string
while(dataFromClient.indexOf(",")!=-1){
  // take the substring from the start to the first occurence of a comma, convert it to int and save it in the array
  data[ data_num ] = dataFromClient.substring(0,dataFromClient.indexOf(",")).toInt();
  data_num++; // increment our data counter
  //cut the data string after the first occurence of a comma
  dataFromClient = dataFromClient.substring(dataFromClient.indexOf(",")+1);
}
// get the last value out of the string, which as no more commas in it
data[ data_num ] = dataFromClient.toInt();

在这段代码中,字符串被消耗,直到字符串中只剩下最后一个值。如果要将数据保留在字符串中,可以将位置变量定义为子字符串起点,并在每个循环周期将其更新到下一个逗号之后的位置

【讨论】:

  • 如果这解决了您的问题,请接受答案。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-21
相关资源
最近更新 更多