hkvega hkvega - 1 month ago 6
C Question

c remove the first character of an array

I have a string:

str1 = "abcabcabc";


How can I remove the first character? I would like the end result to be:

str1 = "bcabcabc";

Answer

If you have a character pointer to a string like:

char *s = "This is my string";

then you can just do s++.

If you have a character array, your best bet may be to have a pointer to that array as well:

char s[] = "This is my string";
char *ps = s;

then you can do ps++ and make sure you use ps rather than s.

If you don't want to have a separate pointer to your array then you can use memmove to copy the data:

memmove (s, s+1, strlen (s+1) + 1); // or just strlen (s)

though none of those will work for an initially empty string so you'll have to check that first. Also keep in mind it's not advisable to attempt modifying string literals in this way (or any way, really) since it's undefined as to whether that's allowed.

Another solution is to simply code up a loop:

for (char *ps = s; *ps != '\0'; ps++)
    *ps = *(ps+1);
*ps = '\0';

This will work for all strings, empty or otherwise.

Comments