【问题标题】:Replace all occurrences of letter in an array of strings替换字符串数组中所有出现的字母
【发布时间】:2021-12-27 00:48:41
【问题描述】:

如何在字符串数组中的字符串中找到单个字符?我需要把它换成另一个字母。给定一个数组

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

我需要替换每个单词中的单个字符(假设是字母'l',然后改为字母'x'),这样数组就变成了

{"hexxo","my","name","is","xukas"}

【问题讨论】:

  • 您遍历数组,然后使用正则表达式替换或std::string::find 来查找和替换您想要更改的字符。

标签: c++ string algorithm replace char


【解决方案1】:

例如,您可以使用基于范围的 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' );
               } );

【讨论】:

    【解决方案2】:

    使用范围视图和算法,您可以轻松做到

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

    这是demo

    【讨论】:

      猜你喜欢
      • 2012-08-01
      • 2012-10-10
      • 2022-11-21
      • 1970-01-01
      • 2017-03-20
      • 2013-12-06
      • 1970-01-01
      • 2013-04-15
      • 2019-02-11
      相关资源
      最近更新 更多