這裏串的位置是一個程序來接受:從用戶在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