Strip first and last character from C string

igul222 picture igul222 · Nov 13, 2009 · Viewed 115.6k times · Source

I have a C string that looks like "Nmy stringP", where N and P can be any character. How can I edit it into "my string" in C?

Answer

pmg picture pmg · Nov 13, 2009

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) */