C++获取某个字符串在控制台中的位置
在C++中,可以使用std::string类来表示字符串,并使用std::string::find函数来获取某个字符串在另一个字符串中的位置。下面是一个示例代码:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
std::string searchStr = "world";
size_t found = str.find(searchStr);
if (found != std::string::npos) {
std::cout << "字符串 \"" << searchStr << "\" 在字符串 \"" << str << "\" 中的位置是 " << found << std::endl;
} else {
std::cout << "字符串 \"" << searchStr << "\" 在字符串 \"" << str << "\" 中未找到" << std::endl;
}
return 0;
}
输出:
字符串 "world" 在字符串 "Hello, world!" 中的位置是 7
在上述代码中,std::string::find函数会返回找到的字符串的起始位置。如果没有找到字符串,函数会返回std::string::npos
原文地址: https://www.cveoy.top/t/topic/iyCt 著作权归作者所有。请勿转载和采集!