C++の文字列の中での文字列検索の方法を教えてください
C++ では文字列を検索するメソッドを提供しています。
- string
- 検出()
- std::string
- 見つけ出す
- 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;
}
- strstr()
- 日本語でそのまま言い換えると
- strstr()
- 元々、民族意識は生まれつきのものではなく、形成されるものであり、その形成には教育が重要な役割を担っていた。
#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;
}