【发布时间】:2011-01-21 17:20:12
【问题描述】:
如何用 C 删除字符串的前三个字母?
【问题讨论】:
-
“请发送密码!!1” - “没有。”
-
str = str + 3;因为str+=3;太短,无法发表评论!
如何用 C 删除字符串的前三个字母?
【问题讨论】:
str = str + 3; 因为str+=3; 太短,无法发表评论!
给指针加3:
char *foo = "abcdef";
foo += 3;
printf("%s", foo);
将打印“def”
【讨论】:
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);
}
另一种设计:
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);
}
【讨论】:
size_t 就像输入一样。
例如,如果你有
char a[] = "123456";
删除前 3 个字符的最简单方法是:
char *b = a + 3; // the same as to write `char *b = &a[3]`
b 将包含“456”
但在一般情况下,您还应该确保不超过字符串长度
【讨论】:
sizeof(char) 不仅无用,对于其他类型也是错误。指针运算以元素为单位进行,而不是字节。
好吧,了解一下字符串复制 (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.
【讨论】:
在 C 中,字符串是连续位置的字符数组。我们不能增加或减少数组的大小。但是创建一个原始大小减 3 的新 char 数组并将字符复制到新数组中。
【讨论】: