How can I remove the ‘\n’ from each string in this array?
I know that I can do something like this for a simple C-String, but I failed at using it in this case
cmd[strcspn(cmd, "\n")] = '\0';
I am also not sure if that would be the propper way or not.
The String will never contain any space or \n in the middle. They are also of a static length (6).
#include <stdlib.h>
unsigned char cmd[][6] = {
{"r123\n"},
{"r999\n"},
{"l092\n"},
{"l420\n"}};
void main(void) {
int i;
for(i = 0; i < (sizeof(cmd) / sizeof(cmd[0])); i++) {
printf("%s\n", cmd[i]);
}
}
Just do it by hand, it’s easy!
If it’s guaranteed to be only the last char in every word, and it’s guaranteed to be there, than like this:
If, on the other hand, you are unsure how many whitespace characters there will be at the end, but you know they will only be there at the end (there might be 0 in this case!) than this:
Voila!
If there will be whitespaces in the middle, then you have to define the desired behaviour: cut only the trailing whitespaces, cut the string in many little ones, or something completely different.
Oh, and one other sidenote:
everyone else seems to be using
char = '\0'. InC,'\0' and 0are equivalent, i.e.if ('\0' == 0) { ... }evaluates to true.Sidenote 2: I used
elem_numberbecause I did not know if the number of elements is a parameter or hardcoded / know in advance. Substitute with what is appropriate.