开发者

Arduino: String join?

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 doin开发者_Python百科g wrong here?


This line

const String args[3] = {"foo", "bar", "baz"};

gives you the strings

"foo\0" "bar\0" "baz\0"

where the \0 is the NULL character. So when you concat, I expect you're ending up with:

"foo\0bar\0baz\0"

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"


The following code works as intended using the Arduino software version 0022 and an Arduino Duemilanove w/ ATmega 328:

#define ARG_DELIMITER ','

class SlaveTalkClass
{
  public:
    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);
    }
} SlaveTalk;

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  const String args[3] = {"foo", "bar", "baz"};
  Serial.println(SlaveTalk.join(args, 3));
}

It repeatedly prints the following to the Serial Monitor:

foo,
foo,bar,
foo,bar,baz,
foo,bar,baz


PString is an excellent library that can concat. It has some neat features, and above all, is runtime safe.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜