字符串的遍历和替换操作

字符串的遍历

使用范围基于的 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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值