如何在C中截断
使用Xcode 如何删除字符串中的前x个字符,其中x是有限值 例如,如果我有一个字符串:如何在C中截断,c,string,C,String,使用Xcode 如何删除字符串中的前x个字符,其中x是有限值 例如,如果我有一个字符串: s = 123.456.789 如何删除要生成的前4个字符: s = 456.789 救命啊 试试看。不假思索地应用这种方法为不小心开始使用动态分配内存的人设置了一个陷阱;如图所示,它没有任何问题,但是如果字符串位于malloced内存中,请注意丢失freeable句柄。在大多数实现中,如果应用于自动字符串(即“s在代码中。@dmckee,我同意你的看法。但是,当你声明这样的字符串时,它应该声明为“c
s = 123.456.789
如何删除要生成的前4个字符:
s = 456.789
救命啊
试试看。不假思索地应用这种方法为不小心开始使用动态分配内存的人设置了一个陷阱;如图所示,它没有任何问题,但是如果字符串位于
malloc
ed内存中,请注意丢失free
able句柄。在大多数实现中,如果应用于自动字符串(即“
s在代码中。@dmckee,我同意你的看法。但是,当你声明这样的字符串时,它应该声明为“const char*”。这个函数使用“char*”,你可以安全地发送可修改的字符串。我将更新我的示例以反映这一点。
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;
}
char *tmp=strdup(oldstr);
strcpy(oldstr, &tmp[4]); // copy from character # 5 back into old string
free(tmp);
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;
}