c remove the first character of an array

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.


Pointer tricks (zero-cost):

char* s = "abcd";
char* substr = s + 1;
// substr == "bcd"

Or:

char s[] = "abcd";
char* substr = s + 1;
// substr == "bcd"

In-place via memmove:

char s[] = "abcd";
char* substr = s + 1;
memmove(s, substr, strlen(substr) + 1);
// s == "bcd"

Notice that we must use char[] rather than char*, which would refer to read-only memory, as described here. Furthermore, one should not use strcpy in-place because the src and dest must not overlap for strcpy.


Into a new string via strcpy:

char* src = "abcd";
char* substr = src + 1;
char dest[strlen(substr) + 1];
strcpy(dest, substr);
// dest == "bcd"

Into a new string via C++'s std::string::substr:

std::string src = "abcd";
std::string dest = src.substr(1);
// dest == "bcd"

Into a new string via C++'s std::copy:

std::string src = "abcd";
std::string dest;
std::copy(src.begin() + 1, src.end(), std::back_inserter(dest));
// dest == "bcd"

There's a couple dozen other ways (particularly when including C++), but I'll stop here. :)

Tags:

C