String Theory

Preamble

Found a great source of information about using the String class in Arduino, in this article, The Evils of Arduino Strings, from Majenko‘s site.

Links

This is also useful for clearing up any confusion: Difference between const char *p, char * const p and const char * const p.

For converting tips, see answers to Problems on convert byte[] to String.

Takeaways

String class

  • Try to avoid using the String class and using native C strings instead
  • Pass String class references to functions and not a copy (i.e. use &)

C strings

  • Use const char *stringname for any C string that will not be manipulated, in declarations and as function parameters
  • USe char stringname[] for strings that can be manipulated, as this places them in RAM

Declaring C strings

  1. char string[30]; – RAM based string, able to be manipulated
  2. char string[30] = "This is text";
  3. char string[30] = {'T','h','i','s',' ','i','s',' ','t','e','x','t','\0'};
  4. char string[]; –
  5. char string[] = "This is text"; – RAM based string, able to be manipulated, string created of the correct length
  6. char string[] = {'T','h','i','s',' ','i','s',' ','t','e','x','t','\0'};
  7. char *string; – pointer to a string
  8. const char *string = "This is text"; – for a string that can and must/should not be manipulated

To print a C string

From Passing a C string and using it:

void PrintString(const char *str) {
    const char *p = str;
    while (*p)
        Serial.print(*p++);
}

or shorter still, use any of these one liners:

  • for(i=0; str[i] && Serial.print(str[i]); ++i)
  • for(i=0; str[i]; Serial.print(str[i++]));
  • while (*str) Serial.print(*str++);

Or, for readability:

void PrintString (const char *str) 
{
    for(const char* p=str; *p != '\0'; p++)
    {
        Serial.print(*p);
    }
}

To print a String

Four ways to print a String (from Serial.print a string object)

void setup() {
  Serial.begin(115200);
  String str = "A String";

  // First
  Serial.println(str);

  // Second
  for(int i=0; i<str.length(); i++) {
    Serial.print(str.charAt(i));
  }
  Serial.println();

  // Third
  Serial.println(str.c_str());

  // Fourth
  for(const char* p=str.c_str(); *p; ) {
    Serial.print(*p++);
  }
  Serial.println();
}
void loop() {}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s