209

文字列にCの部分文字列が含まれているかどうかを確認しようとしています:

char *sent = "this is my sample example";
char *word = "sample";
if (/* sentence contains word */) {
    /* .. */
}

string::findC++の代わりに使用するものは何ですか?

4

12 に答える 12

332
if(strstr(sent, word) != NULL) {
    /* ... */
}

単語が見つかった場合、単語strstrの先頭へのポインターを返すことに注意してください。sentword

于 2012-10-08T15:30:23.003 に答える
35

これに使用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)
{
    ...
}
于 2012-10-08T15:30:40.023 に答える
3

このコードは、既製の関数を使用せずに、検索がどのように機能するか (方法の 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;
}
于 2015-02-13T02:55:49.830 に答える
2

この単純なコードでも同じことが達成されます: これらを使用する理由:

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;
}

しかし、トリッキーな部分は、元の文字列のどの位置で部分文字列が始まるかを報告することです...

于 2014-09-26T09:18:51.250 に答える