【问题标题】:How to remove first three characters from string with C?如何用C从字符串中删除前三个字符?
【发布时间】:2011-01-21 17:20:12
【问题描述】:

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

【问题讨论】:

  • “请发送密码!!1” - “没有。”
  • str = str + 3; 因为str+=3; 太短,无法发表评论!

标签: c string


【解决方案1】:

给指针加3:

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

将打印“def”

【讨论】:

  • 需要先检查以确保其长度至少为三个字符!
【解决方案2】:
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);
}

【讨论】:

  • +1,但它不是 int 更好,它打印实际剩余的字符数(或 -1 而不是断言)?
  • @Tim:有各种可能的设计;这是一个大致最小的实现——总的来说,我认为分配比提前返回要好。至于返回值 - 我可以返回减少的长度 - 这很可能是 size_t 就像输入一样。
【解决方案3】:

例如,如果你有

char a[] = "123456";

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

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

b 将包含“456”

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

【讨论】:

  • sizeof(char) 不仅无用,对于其他类型也是错误。指针运算以元素为单位进行,而不是字节。
【解决方案4】:

好吧,了解一下字符串复制 (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.

【讨论】:

  • -1。没有解释的代码比引用链接和完全明显的“伪代码”要好。
【解决方案5】:

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

【讨论】:

  • 这将复制字符串的前三个字符。该问题询问如何删除前三个字符。
  • 是的,刚刚注意到。已更改。谢谢。
猜你喜欢
  • 2014-03-21
  • 2011-11-03
  • 2012-08-02
  • 1970-01-01
  • 2012-07-13
  • 2011-10-15
  • 2011-05-16
  • 2017-09-09
  • 1970-01-01
相关资源
最近更新 更多