Reputation: 2282
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]);
}
}
Upvotes: 2
Views: 1483
Reputation: 8418
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:
for (i = 0; i < elem_number; ++i){
cmd[i][strlen(cmd[i])-1] = 0;
}
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:
for (i = 0; i < elem_number; ++i){
for (j = 0; cmd[i][j] != 0; ++j){
if (isspace(cmd[i][j]))
cmd[i][j] = 0;
}
}
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'
. In C
, '\0' and 0
are equivalent, i.e. if ('\0' == 0) { ... }
evaluates to true.
Sidenote 2: I used elem_number
because I did not know if the number of elements is a parameter or hardcoded / know in advance. Substitute with what is appropriate.
Upvotes: 2
Reputation: 10756
Setting a character in a char array to \0
will truncate the string at that character.
So in your example setting the 5th character will do the job.
cmd[i][4] = '\0';
If the intended string can be less than 4 in length then don't hard-code to 4 but rather strlen(cmd[i])-1
Upvotes: 1
Reputation: 40145
for(i = 0; i< sizeof(cmd)/sizeof(unsigned char[6]);i++)
*strchr(cmd[i], '\n') = '\0';
Upvotes: -1
Reputation: 409166
Maybe you can use strrchr
? Use in a loop if the string may contain several linebreaks.
Upvotes: 0