简体   繁体   English

使用strstr确定给定的字符串是否包含带空格的字符串[C]

[英]Using strstr to determine if a given string contains a string with spaces [C]

I'm working through an example of using the strstr() function. 我正在研究一个使用strstr()函数的示例。

If I input "Pamela Sue Smith", why does the program output ""Pamela" is a sub-string!" 如果输入“ Pamela Sue Smith”,为什么程序输出“” Pamela“是子字符串!” and not ""Pamela Sue Smith" is a sub-string!". 而不是““ Pamela Sue Smith”是子字符串!“。

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

void main(void)
{
  char str[72];
  char target[] = "Pamela Sue Smith";

  printf("Enter your string: ");
  scanf("%s", str);

  if (strstr( target, str) != NULL )
    printf(" %s is a sub-string!\n", str);
}
  1. main does not have return-type void but int . main没有return类型的void但是有int
  2. scanf can fail. scanf可能会失败。 Check the return-value. 检查返回值。
    If successful, it returns the number of parameters assigned. 如果成功,它将返回分配的参数数量。
  3. %s only reads non-whitespace, until the next whitespace (thus 1 word). %s仅读取非空白,直到下一个空白(因此为1个字)。
  4. %s does not limit how many non-whitespace characters are read. %s不限制读取多少个非空白字符。 A buffer-overflow can be deadly. 缓冲区溢出可能是致命的。
    Use %71s (buffer-size: string-length + 1 for the terminator) 使用%71s (缓冲区大小:字符串长度+ 1作为终止符)
  5. You swapped the arguments to strstr . 您将参数交换为strstr

From the manual page for scanf : scanf的手册页中:

“s” — Matches a sequence of non-white-space characters; “ s”-匹配一系列非空格字符; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null byte ('\\0'), which is added automatically. 下一个指针必须是指向字符数组的指针,该指针必须足够长以容纳输入序列和终止的空字节('\\ 0'),该字符会自动添加。 The input string stops at white space or at the maximum field width, whichever occurs first. 输入字符串停在空白处或最大字段宽度处,以先到者为准。

So, the part “Sue Smith” never makes it to str . 因此,“苏·史密斯”这一部分从来​​没有达到str You could use fgets which allows you to read a whole line at a time: 您可以使用fgets来一次读取整行:

if (fgets(str, sizeof str, stdin) == NULL) {
    printf("End of file\n");
    return;
}

Note that in this case, str contains the terminating end-of-line character. 请注意,在这种情况下, str包含终止行尾字符。 You could do 你可以做

if (*str != '\0')
    str[strlen(str) - 1] = '\0';

to remove it. 删除它。 (Also, as some others already pointed out, the “haystack” argument to strstr goes first.) (此外,正如其他人已经指出的那样,对strstr的“干草堆”争论首先出现。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM