C++におけるstrstr関数の使い方は何ですか。

C++の中で、strstr関数は文字列内で指定された部分文字列の位置を検索するために使用されます。そのプロトタイプは以下の通りです:

char* strstr(const char* str1, const char* str2);

str1は検索される文字列であり、str2は検索されるサブ文字列です。strstr関数は、str2が最初に現れる位置を指すポインタを返しますが、見つからない場合はnullptrを返します。

サンプルコード:

#include <iostream>
#include <cstring>

int main() {
    const char* str1 = "Hello, world!";
    const char* str2 = "world";

    char* result = strstr(str1, str2);

    if (result) {
        std::cout << "Found at position: " << result - str1 << std::endl;
    } else {
        std::cout << "Not found" << std::endl;
    }

    return 0;
}

結果は出力されました:

Found at position: 7
コメントを残す 0

Your email address will not be published. Required fields are marked *


广告
広告は10秒後に閉じます。
bannerAds