Strip first and last character from C string
I have a C string that looks like "Nmy stringP"
, where N and P can be any character. How can I edit it into "m开发者_StackOverflowy string"
in C?
To "remove" the 1st character point to the second character:
char mystr[] = "Nmy stringP";
char *p = mystr;
p++; /* 'N' is not in `p` */
To remove the last character replace it with a '\0'
.
p[strlen(p)-1] = 0; /* 'P' is not in `p` (and it isn't in `mystr` either) */
Another option, again assuming that "edit" means you want to modify in place:
void topntail(char *str) {
size_t len = strlen(str);
assert(len >= 2); // or whatever you want to do with short strings
memmove(str, str+1, len-2);
str[len-2] = 0;
}
This modifies the string in place, without generating a new address as pmg's solution does. Not that there's anything wrong with pmg's answer, but in some cases it's not what you want.
Further to @pmg's answer, note that you can do both operations in one statement:
char mystr[] = "Nmy stringP";
char *p = mystr;
p++[strlen(p)-1] = 0;
This will likely work as expected but behavior is undefined in C standard.
The most efficient way:
//Note destroys the original string by removing it's last char
// Do not pass in a string literal.
char * getAllButFirstAndLast(char *input)
{
int len = strlen(input);
if(len > 0)
input++;//Go past the first char
if(len > 1)
input[len - 2] = '\0';//Replace the last char with a null termination
return input;
}
//...
//Call it like so
char str[512];
strcpy(str, "hello world");
char *pMod = getAllButFirstAndLast(str);
The safest way:
void getAllButFirstAndLast(const char *input, char *output)
{
int len = strlen(input);
if(len > 0)
strcpy(output, ++input);
if(len > 1)
output[len - 2] = '\0';
}
//...
//Call it like so
char mod[512];
getAllButFirstAndLast("hello world", mod);
The second way is less efficient but it is safer because you can pass in string literals into input. You could also use strdup for the second way if you didn't want to implement it yourself.
精彩评论