24

How would I remove the first three letters of a string with C?

2
  • 4
    "plz send teh codez!!1" - "No."
    – user395760
    Commented Jan 21, 2011 at 17:21
  • 8
    str = str + 3; since str+=3; is too short for a comment! Commented Jan 21, 2011 at 17:23

5 Answers 5

36

Add 3 to the pointer:

char *foo = "abcdef";
foo += 3;
printf("%s", foo);

will print "def"

1
  • 7
    Need to check to make sure it's at least three characters long first!
    – kindall
    Commented Jan 21, 2011 at 17:26
18
void chopN(char *str, size_t n)
{
    assert(n != 0 && str != 0);
    size_t len = strlen(str);
    if (n > len)
        return;  // Or: n = len;
    memmove(str, str+n, len - n + 1);
}

An alternative design:

size_t chopN(char *str, size_t n)
{
    assert(n != 0 && str != 0);
    size_t len = strlen(str);
    if (n > len)
        n = len;
    memmove(str, str+n, len - n + 1);
    return(len - n);
}
2
  • +1, but wouldn't it be better as int, which prints the # of chars actually remaining (or -1 instead of the assertion) ?
    – user50049
    Commented Jan 21, 2011 at 18:35
  • @Tim: there are all sorts of possible designs; this is a roughly minimal implementation - on the whole, I think the assignment is better than the early return. As to the return value - I'd be fine with returning the reduced length - that would be size_t like the input, most likely. Commented Jan 21, 2011 at 19:09
11

For example, if you have

char a[] = "123456";

the simplest way to remove the first 3 characters will be:

char *b = a + 3;  // the same as to write `char *b = &a[3]`

b will contain "456"

But in general case you should also make sure that string length not exceeded

1
  • 1
    Not only is sizeof(char) useless, it's also wrong for other types. Pointer arithmetic takes place in units of elements, not bytes. Commented Jan 21, 2011 at 18:25
0

Well, learn about string copy (http://en.wikipedia.org/wiki/Strcpy), indexing into a string (http://pw1.netcom.com/~tjensen/ptr/pointers.htm) and try again. In pseudocode:

find the pointer into the string where you want to start copying from
copy from that point to end of string into a new string.
1
  • 2
    -1. Code without explanation is better than links to references and completely obvious "pseudocode".
    – darda
    Commented Jan 30, 2014 at 18:21
0

In C, string is an array of characters in continuous locations. We can't either increase or decrease the size of the array. But make a new char array of size of original size minus 3 and copy characters into new array.

2
  • 1
    That'll copy the first three characters of the string. The question asks how to remove the first three characters.
    – mipadi
    Commented Jan 21, 2011 at 17:30
  • Yeah Just noticed.Changed it. Thanks.
    – Mahesh
    Commented Jan 21, 2011 at 17:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.