文字列にCの部分文字列が含まれているかどうかを確認しようとしています:
char *sent = "this is my sample example";
char *word = "sample";
if (/* sentence contains word */) {
/* .. */
}
string::find
C++の代わりに使用するものは何ですか?
if(strstr(sent, word) != NULL) {
/* ... */
}
単語が見つかった場合、単語strstr
の先頭へのポインターを返すことに注意してください。sent
word
これに使用strstr
します。
http://www.cplusplus.com/reference/clibrary/cstring/strstr/
だから、あなたはそれを次のように書くでしょう..
char *sent = "this is my sample example";
char *word = "sample";
char *pch = strstr(sent, word);
if(pch)
{
...
}
このコードは、既製の関数を使用せずに、検索がどのように機能するか (方法の 1 つ) のロジックを実装します。
public int findSubString(char[] original, char[] searchString)
{
int returnCode = 0; //0-not found, -1 -error in imput, 1-found
int counter = 0;
int ctr = 0;
if (original.Length < 1 || (original.Length)<searchString.Length || searchString.Length<1)
{
returnCode = -1;
}
while (ctr <= (original.Length - searchString.Length) && searchString.Length > 0)
{
if ((original[ctr]) == searchString[0])
{
counter = 0;
for (int count = ctr; count < (ctr + searchString.Length); count++)
{
if (original[count] == searchString[counter])
{
counter++;
}
else
{
counter = 0;
break;
}
}
if (counter == (searchString.Length))
{
returnCode = 1;
}
}
ctr++;
}
return returnCode;
}
この単純なコードでも同じことが達成されます: これらを使用する理由:
int main(void)
{
char mainstring[]="The quick brown fox jumps over the lazy dog";
char substring[20];
int i=0;
puts("enter the sub stirng to find");
fgets(substring, sizeof(substring), stdin);
substring[strlen(substring)-1]='\0';
if (strstr(mainstring,substring))
{
printf("substring is present\t");
}
printf("and the sub string is:::");
printf("%s",substring,"\n");
return 0;
}
しかし、トリッキーな部分は、元の文字列のどの位置で部分文字列が始まるかを報告することです...