How to remove first three characters from string w

2020-06-02 07:46发布

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

标签: c string
5条回答
小情绪 Triste *
2楼-- · 2020-06-02 08:12

Add 3 to the pointer:

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

will print "def"

查看更多
狗以群分
3楼-- · 2020-06-02 08: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);
}
查看更多
干净又极端
4楼-- · 2020-06-02 08:18

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

查看更多
叛逆
5楼-- · 2020-06-02 08:30

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.

查看更多
The star\"
6楼-- · 2020-06-02 08:31

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.
查看更多
登录 后发表回答