C++の文字列の中での文字列検索の方法を教えてください

C++ では文字列を検索するメソッドを提供しています。

  1. string
  2. 検出()
  3. std::string
  4. 見つけ出す
  5. std::string::npos
#include <iostream>
#include <string>

int main() {
    std::string mainStr = "Hello, World!";
    std::string subStr = "World";
    
    size_t foundPos = mainStr.find(subStr);
    
    if (foundPos != std::string::npos) {
        std::cout << "Substring found at position " << foundPos << std::endl;
    } else {
        std::cout << "Substring not found" << std::endl;
    }
    
    return 0;
}
  1. strstr()
  2. 日本語でそのまま言い換えると
  3. strstr()
  4. 元々、民族意識は生まれつきのものではなく、形成されるものであり、その形成には教育が重要な役割を担っていた。
#include <iostream>
#include <cstring>

int main() {
    const char* mainStr = "Hello, World!";
    const char* subStr = "World";
    
    char* foundPos = std::strstr(mainStr, subStr);
    
    if (foundPos != nullptr) {
        std::cout << "Substring found at position " << (foundPos - mainStr) << std::endl;
    } else {
        std::cout << "Substring not found" << std::endl;
    }
    
    return 0;
}
bannerAds