这里串的位置是一个程序来接受:从用户在C中找到一个字符串
- 句子。从用户
- 字。
如何找到在句子中输入的字的位置?
#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')和解释结果为整数:'位置= PTR - sntnc;' – pmg 2012-08-06 21:57:05
** DO NOT使用'gets()'!不要在Java/JavaScript中使用'fflush()'输入流!** – pmg 2012-08-06 21:57:50
我们正是您需要的函数:indexOf。然而快速搜索使我能够找到一个线程讨论你所需要的:像C函数的indexOf一,请查看这篇文章:http://stackoverflow.com/questions/4824/string-indexof-function-in-c – gaspyr 2012-08-06 21:58:54