替换字符串数组中所有出现的字母

3

如何在字符串数组中找到一个单个字符并将其替换为另一个字符? 给定一个数组

string A[5] = {"hello","my","name","is","lukas"};

我需要替换每个单词中的一个字符(比如说字母'l',替换为字母'x'),以便数组变成:
{"hexxo","my","name","is","xukas"}

1
你可以通过循环遍历数组,然后使用正则表达式替换或 std::string::find 查找和替换你想要改变的字符。 - NathanOliver
2个回答

3

你可以使用基于范围的for循环来执行此任务。

for ( auto &s : A )
{
    for ( auto &c : s )
    {
        if ( c == 'l' ) c = 'x';
    }
}

你可以使用标准算法std::replace代替内部循环。例如:

#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>

int main()
{
    std::string A[5] = { "hello","my","name","is","lukas" };

    for (auto &s : A)
    {
        std::replace( std::begin( s ), std::end( s ), 'l', 'x' );
    }

    for (const auto &s : A)
    {
        std::cout << s << ' ';
    }
    std::cout << '\n';
}

程序输出为:
hexxo my name is xukas

或者你可以使用标准算法std::for_each代替这两个循环,像这样:

std::for_each( std::begin( A ), std::end( A ),
               []( auto &s )
               {
                   std::replace( std::begin( s ), std::end( s ), 'l', 'x' );
               } );

1

通过使用范围视图和算法,您可以轻松地完成

std::ranges::replace(A | std::views::join, 'l', 'x');

这里有一个演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接