2

strchr在使用 char 指针找到第一次出现后,我试图再获得 2 个字符。该字符串可能如下所示:

foo;bar;2012 -> should output foo;b
foo;caz;     -> should output foo;c
foo;         -> should output foo (there are no +2 chars)
foo          -> null

对于第一种情况,我想我可以做类似的事情,

#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] = "foo;bar;2012";
  char *pch = NULL;

  if ((pch=strchr(str,';')) != NULL) {
    *pch++;
    *pch++;
    *pch = '\0';
  }
  puts(str);
  return 0;
}

但是检查我是否可以在字符串中推进指针而不越过的正确方法是什么?

4

1 回答 1

3

这些*pch++行应该生成编译器警告(如果没有,则说明您没有在编译时启用足够的警告)。我编译时将警告视为错误,所以我得到:

xw31.c:10:5: error: value computed is not used [-Werror=unused-value]
     *pch++;

您应该使用pch++;— 不读取但忽略该值。

您应该检查您在访问超出您的位置时没有到达字符串末尾strstr(),因此可以使用:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char str[] = "foo;bar;2012";
    char *pch;

    if ((pch = strchr(str, ';')) != NULL)
    {
        if (pch[1] != '\0' && pch[2] != '\0')
            pch[3] = '\0';
        puts(str);
    }
    return 0;
}

如果内部测试失败,则字符串已经足够短。 pch[0]当然是分号。这生foo;ba成为输出。如果你只想要foo;b,那么你只需要提前少测试一个字符:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char str[] = "foo;bar;2012";
    char *pch;

    if ((pch = strchr(str, ';')) != NULL)
    {
        if (pch[1] != '\0')
            pch[2] = '\0';
        puts(str);
    }
    return 0;
}
于 2016-05-30T03:14:59.340 回答