Mug*_*mbo 7 c string substring strstr
这是一个接受的程序:
如何找到句子中输入单词的位置?
#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;
}
Run Code Online (Sandbox Code Playgroud)
Gin*_*ngi 19
该ptr
指针将指向的开头word
,所以你可以只减去了一句指针的位置,sntnc
从它:
pos = ptr - sntnc;
Run Code Online (Sandbox Code Playgroud)
仅供参考:
char saux[] = "this is a string, try to search_this here";
int dlenstr = strlen(saux);
if (dlenstr > 0)
{
char *pfound = strstr(saux, "search_this"); //pointer to the first character found 's' in the string saux
if (pfound != NULL)
{
int dposfound = int (pfound - saux); //saux is already pointing to the first string character 't'.
}
}
Run Code Online (Sandbox Code Playgroud)