字符串的遍历
使用范围基于的 for 循环(C++11 及以后)
格式:(遍历字符串s)
for(char c:s)
{
std::cout << c << std::endl;
}
例:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
for (char c : str) {
std::cout << c << std::endl;
}
return 0;
}
普通的for循环遍历
格式:(遍历字符串s)
for(size_t i=0;i<s.size;i++)//size_t 是一个无符号整数类型,通常用于表示大小或数量。
{
std::cout << s[i] << std::endl;
}
例:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
for (size_t i = 0; i < str.size(); ++i) {
std::cout << str[i] << std::endl;
}
return 0;
}
替换字符串中的字符
使用索引直接替换
直接根据字符的下标替换
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
str[7] = 'W'; // 将 'W' 替换为 'W'(示例)
std::cout << str << std::endl; // 输出: Hello, World!
return 0;
}
使用 std::replace
std::replace
函数可以替换字符串中所有指定的字符:
#include <iostream>
#include <string>
#include <algorithm> // 包含 std::replace
int main() {
std::string str = "Hello, World!";
std::replace(str.begin(), str.end(), 'o', 'a'); // 将所有 'o' 替换为 'a'
std::cout << str << std::endl; // 输出: Hella, Warld!
return 0;
}
使用 std::replace_if
std::replace_if
函数可以基于条件替换字符串中的字符:
#include <iostream>
#include <string>
#include <algorithm> // 包含 std::replace_if
int main() {
std::string str = "Hello, World!";
std::replace_if(str.begin(), str.end(), [](char c) { return c == 'o'; }, 'a'); // 将所有 'o' 替换为 'a'
std::cout << str << std::endl; // 输出: Hella, Warld!
return 0;
}
使用 std::string::replace
方法
std::string::replace
方法可以替换字符串中指定范围内的字符:
cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
str.replace(7, 5, "Earth"); // 从索引 7 开始,替换 5 个字符为 "Earth"
std::cout << str << std::endl; // 输出: Hello, Earth!
return 0;
}
示例:遍历并替换特定字符
假设你想要遍历字符串并替换所有的 'o' 为 'a',可以结合遍历和替换操作:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
for (size_t i = 0; i < str.size(); ++i) {
if (str[i] == 'o') {
str[i] = 'a';
}
}
std::cout << str << std::endl; // 输出: Hella, Warld!
return 0;
}