C语言 如何用C从字符串中删除前三个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4761764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:34:12  来源:igfitidea点击:

How to remove first three characters from string with C?

cstring

提问by BlackBear

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

如何用 C 删除字符串的前三个字母?

采纳答案by Jonathan Leffler

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);
}

回答by BlackBear

Add 3 to the pointer:

将 3 添加到指针:

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

will print "def"

将打印“def”

回答by Martin Babacaev

For example, if you have

例如,如果你有

char a[] = "123456";

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

删除前 3 个字符的最简单方法是:

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

b will contain "456"

b 将包含“456”

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

但在一般情况下,您还应该确保不超过字符串长度

回答by Mahesh

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.

在 C 中,字符串是连续位置的字符数组。我们不能增加或减少数组的大小。但是创建一个原始大小减 3 大小的新字符数组,并将字符复制到新数组中。

回答by I82Much

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:

好吧,了解字符串复制 ( http://en.wikipedia.org/wiki/Strcpy),索引到字符串 ( http://pw1.netcom.com/~tjensen/ptr/pointers.htm)并重试。在伪代码中:

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.