c - Arduino(C语言)解析带分隔符的字符串(通过串口输入)

标签 c string parsing arduino delimiter

Arduino(C语言)解析带分隔符的字符串(通过串口输入)

没有在这里找到答案:/

我想通过串行接口(interface) (Serial.read()) 向我的 arduino 发送一个由逗号分隔的三个数字组成的简单字符串。这三个数字的范围可以是 0-255。

例如。 255,255,255 0,0,0 1,20,100 90,200,3

我需要做的是将发送到 arduino 的字符串解析为三个整数(比如 r、g 和 b)。

所以当我发送 100,50,30 arduino 会将其翻译成

int r = 100
int g = 50
int b = 30

我尝试了很多代码,但没有一个有效。主要问题是将字符串(字符束)转换为整数。我发现可能会有 strtok_r 用于分隔符目的,但仅此而已。

感谢您的任何建议:)

最佳答案

要回答您实际提出的问题,String 对象非常强大,它们可以完全满足您的要求。如果您直接从输入中限制解析规则,您的代码将变得不那么灵活、可重用性降低并且稍微复杂。

字符串有一个名为 indexOf() 的方法,它允许您在字符串的字符数组中搜索特定字符的索引。如果未找到该字符,该方法应返回 -1。可以将第二个参数添加到函数调用以指示搜索的起点。在你的情况下,由于你的分隔符是逗号,你会调用:

int commaIndex = myString.indexOf(',');
//  Search for the next comma just after the first
int secondCommaIndex = myString.indexOf(',', commaIndex + 1);

然后您可以使用该索引通过 String 类的 substring() 方法创建一个子字符串。这将返回一个新的字符串,从特定的起始索引开始,并在第二个索引之前结束(如果没有给出,则为文件末尾)。所以你会输入类似于:

String firstValue = myString.substring(0, commaIndex);
String secondValue = myString.substring(commaIndex + 1, secondCommaIndex);
String thirdValue = myString.substring(secondCommaIndex + 1); // To the end of the string

最后,可以使用 String 类的未记录方法 toInt() 检索整数值:

int r = firstValue.toInt();
int g = secondValue.toInt();
int b = thirdValue.toInt();

有关 String 对象及其各种方法的更多信息,请参见 Arduino documentation .

关于c - Arduino(C语言)解析带分隔符的字符串(通过串口输入),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11068450/

相关文章:

perl - 如何在Perl 5中定义解析语法?

c - 警告 'return' 无值,函数返回非 void - 它应该返回什么?

python - 在列表中查找字符串第二次出现的索引

string - 有没有办法在 swift 中从 utf16 数组创建字符串?

python - 使用 python 访问 csv 文件中的各个单元格

android - 使用 jsoup 解析抛出错误(NetworkOnMainThreadException)

更改函数中的指针字符值

c - 在没有新 malloc 的情况下从现有字符串动态构造一个数组

c - perl 和 C 脚本的管道

c++ - 无法从 'const std::string [3]' 转换为 'std::string'