Go Down

Topic: char* array get length of string? (Read 87 times) previous topic - next topic

skywatch

Jun 14, 2016, 03:56 pm Last Edit: Jun 14, 2016, 04:28 pm by skywatch
With an array like this.....


char* myStrings[]={"This is string 1", "This is string 2", "This is string 3",
"This is string 4", "This is string 5","This is string 6"};

What is the correct way to get the length of "myStrings
  • " to give the number of characters?


Will it require adding string.h to the sketch?


I am sure it's simple, but I have searched for hours now and still no answer!  :smiley-confuse:


Thanks if you can help!

KeithRB

#1
Jun 14, 2016, 03:59 pm Last Edit: Jun 14, 2016, 03:59 pm by KeithRB
Code: [Select]


size_t l = strlen(myString[0]);


On the arduino, you can almost certainly use int instead of size_t.
string.h is automagically added.

Whandall

Code: [Select]
char* myStrings[] = {"This is string 1", "This is string 2", "This is string 3",
                     "This is string 4", "This is string 5", "This is string 6"
                    };
void setup() {
  Serial.begin(115200);
  int totalLength = sizeof(myStrings);
  Serial.print(F("Size of the array is "));
  Serial.println(totalLength);
  for (byte idx = 0; idx < sizeof(myStrings) / sizeof(myStrings[0]); idx++) {
    int thisLength = strlen(myStrings[idx]) + 1;
    Serial.print(F("Size of element "));
    Serial.print(idx);
    Serial.print(F(" is "));
    Serial.println(thisLength);
    totalLength += thisLength;
  }
  Serial.print(F("Total size of the array and the strings is "));
  Serial.println(totalLength);
}

void loop() {}
Code: [Select]
Size of the array is 12
Size of element 0 is 17
Size of element 1 is 17
Size of element 2 is 17
Size of element 3 is 17
Size of element 4 is 17
Size of element 5 is 17
Total size of the array and the strings is 114
Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. (D.Adams)

KeithRB

He wanted the number of characters, so I assume that that does not include the '\0', though I guess that is technically a character. 8^)

Whandall

Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. (D.Adams)

skywatch

I knew it would be easy ;)

Thank you both for the help!

:) :) :)

Now I only have one other thing to sort out and the project is done!

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy