C++中字符串的查找与替换
字符串的查找是指查看在字符串中是否有另一个指定的子串。
字符串的替换是指将字符串中指定部分替换成指定的内容。
#include <iostream>
int main(int argc,const char* argv[])
{
std::string str1 = "Hello World!";
//在字符串str1中查看是否有字符o,如果有则返回字符o在字符串str1中的位置,否则返回npos
std::cout << str1.find("o") << std::endl;
//在字符串str1中的第五个位置开始向后查找是否有字符o,如果有则返回字符o在字符串str1中的位置
std::cout << str1.find("o",5) << std::endl;
//在字符串str1中从后向前查看是否有字符o,如果有则返回o在字符串str1中的位置
std::cout << str1.rfind("o") <<std::endl;
//在字符串str1中的第五个位置开始从后向前查看是否有字符o,如果有则返回字符o在字符串str1中的位置。
std::cout << str1.rfind("o",5) << std::endl;
std::string str2 = "China";
//将字符串str1中第6个字符开始连续5个字符替换成str2的内容
str1.replace(6,5,str2);
std::cout << str1 << std::endl;
return 0;
}