Arduino:字符串连接?
我正在尝试为 Arduino 编写一个 join
方法:
#define ARG_DELIMITER ','
String join(const String strs[], const int len) {
String result = "";
for (int i = 0; i < len; i++) {
result += strs[i] + ARG_DELIMITER;
Serial.println(result);
}
return result.substring(0, result.length() - 1);
}
loop()
中的调用代码:
const String args[3] = {"foo", "bar", "baz"};
Serial.println(SlaveTalk.join(args, 3));
这会打印以下内容:
foo
foo
foo
fo
只要程序运行,后跟空字符串。
我在这里做错了什么?
I'm trying to write a join
method for the Arduino:
#define ARG_DELIMITER ','
String join(const String strs[], const int len) {
String result = "";
for (int i = 0; i < len; i++) {
result += strs[i] + ARG_DELIMITER;
Serial.println(result);
}
return result.substring(0, result.length() - 1);
}
The calling code in loop()
:
const String args[3] = {"foo", "bar", "baz"};
Serial.println(SlaveTalk.join(args, 3));
This prints the following:
foo
foo
foo
fo
followed by empty strings as long as the program runs.
What am I doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这一行
给出了字符串
,其中 \0 是 NULL 字符。因此,当您连接时,我希望您最终会得到:
打印在 null 处停止,这就是您看到 foo 3 次的原因。在 return 语句中,长度为 3“foo”,减去 1 得到“fo”
This line
gives you the strings
where the \0 is the NULL character. So when you concat, I expect you're ending up with:
The printing stops at the null which is why you see foo 3 times. In the return statement, the length is 3 "foo" and subtracting 1 gives you "fo"
以下代码使用 Arduino 软件版本 0022 和带有 ATmega 328 的 Arduino Duemilanove 按预期工作:
它会重复将以下内容打印到串行监视器:
The following code works as intended using the Arduino software version 0022 and an Arduino Duemilanove w/ ATmega 328:
It repeatedly prints the following to the Serial Monitor:
PString 是一个优秀的可以连接的库。它有一些简洁的功能,最重要的是,它是运行时安全的。
PString is an excellent library that can concat. It has some neat features, and above all, is runtime safe.