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

标签 c++ string algorithm replace char

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

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

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

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

最佳答案

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

关于c++ - 替换字符串数组中所有出现的字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69980728/

相关文章:

c++ - 在 0x1000A456 (glut32.dll) OpenGL 抛出异常

iphone - 字符串中的子串整数

c - 手机数字键盘上可能的字符组合

algorithm - GCJ - 哈密顿循环

c# - 恶霸算法

c++ - 简单的网络编程程序 - 不工作

c++ - Http POST,使用Qt选择页面

c++ - 从 {fmt} 中获得最佳性能

c - 递归函数 : Remove substring from string in C

algorithm - 在 BST 中查找所有小于 x 的数字