【发布时间】:2012-08-03 21:51:20
【问题描述】:
这是一个接受a的程序:
- 来自用户的一句话。
- 用户的话。
如何找到输入的单词在句子中的位置?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char sntnc[50], word[50], *ptr[50];
int pos;
puts("\nEnter a sentence");
gets(sntnc);
fflush(stdin);
puts("\nEnter a word");
gets(word);
fflush(stdin);
ptr=strstr(sntnc,word);
//how do I find out at what position the word occurs in the sentence?
//Following is the required output
printf("The word starts at position #%d", pos);
return 0;
}
【问题讨论】:
-
您可以减去 2 个指针(指向
char)并将结果解释为整数:position = ptr - sntnc; -
不要使用
gets()!不要fflush()输入流! -
在 Java / JavaScript 中,我们正好有你需要的函数:indexOf。然而,通过快速搜索,我找到了一个讨论您需要什么的线程:C 中的类似 indexOf 函数,请查看这篇文章:stackoverflow.com/questions/4824/string-indexof-function-in-c