如何在C中截断

时间:2013-11-17 01:46:32

标签: c string

使用Xcode。

如何删除字符串中的前x个字符,其中x是有限值?

例如,如果我有一个字符串:

s = 123.456.789

如何删除前4个字符:

s = 456.789 

帮助。

3 个答案:

答案 0 :(得分:2)

char *tmp=strdup(oldstr);
strcpy(oldstr, &tmp[4]);  // copy from character # 5 back into old string
free(tmp);

试试。

答案 1 :(得分:1)

 char *s = "123.456.789"
 s += 4;
 printf("%s\n", s); // will print 456.789

答案 2 :(得分:0)

void remove_first_x(char *s, int x) {
    char *p = s+x;
    memmove(s, p, strlen(p)+1);
}

int main() {
    char *str1 = "123.456.789";  // String defined this way should not be modified.
                                 // C++ compiler warns you if you define a string
                                 // like this! Better define it as "const char *".

    char str2[] = "123.456.789"; // String defined this way can be modified

    remove_first_x(str1, 4);     // Not safe!
    remove_first_x(str2, 4);     // Safe!

    return 0;
}