【问题标题】:Search for a word inside a string in C [duplicate]在C中的字符串中搜索单词[重复]
【发布时间】:2014-05-12 11:52:05
【问题描述】:

我在这里有一个新手问题,我想和你一起学习。 我有一个结构数组,在那个数组里面我有一个字符串变量。 我想计算字符串变量中包含“字符串”一词的所有位置。 我的问题是我不知道使用什么 string.h 函数在字符串中搜索单词并计数。

希望你能帮助我。

这是我想要的一个简单示例。

struct _man
{
  char name[50];
  int house_number;
};


void main()
{
  int i=0,count=0;
  struct _man man[20];
  //assuming there is already information inside the array struct
  for(i = 0; i<20;i++)
  {
    if (//function i want to know to search for the word "Jose" inside string  man[i].name)
    {
      count++;
    }
  }
  printf("There is %d people with the word Jose in their name\n",count);
}

【问题讨论】:

  • 谷歌strstr()
  • Searching for your exact title 产生的收益足以让您入门。请在发布到 Stack Overflow 之前进行简单的研究。
  • 您是否考虑过这样的功能可能不存在,而您必须编写它?提示:使用循环。另外,您的标题具有误导性。你说你想搜索一个子字符串,但你真的想countinstances of一个子字符串。
  • 虽然从技术上讲,他确实想要搜索子字符串的第一次出现。然后在此之后第一次出现子字符串。然后在此之后第一次出现子字符串;) 进一步提示>
  • @JoséPedroBrito 哈哈,休息一下,因为在正常情况下发布这个问题可能比发明解决方案花费的时间更多。

标签: c string


【解决方案1】:

strstr()是你需要使用的:

例如:

char * name = "Jose Pedro Birto";
char * toBeMatched = "Pedro";

if (strstr(name, toBeMatched)) {   // or (strstr(name, toBeMatched) != null)
    printf("name contains Pedro");
} else {
    printf("name does not contain Pedro");
}

【讨论】:

  • C 不是 C++。此外,他还想数数。
  • strstr(name, toBeMatched) 是正确的,感谢您的时间;)
  • @JonathonReinhart strstr() 来自 C!我正在使用 C++ cout 输出并没有回答我关于使用 strstr() 不正确的问题,好吗?而且,对于“计数”,您真的阅读过 OP 的问题吗?计数不是问题的一部分。他要求的只是一种查看字符串是否存在于另一个字符串中的方法。
  • 真的不知道投反对票的原因。如果人们仅仅因为我使用 cout 而不是 printf 而认为它无关紧要,那么让我改变它(但老实说这很愚蠢,因为这不是答案的主要部分)
【解决方案2】:

您可以从string.h 使用strstr

【讨论】:

    猜你喜欢
    • 2016-04-26
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    相关资源
    最近更新 更多