Home > Net >  Replace all occurrences of letter in an array of strings
Replace all occurrences of letter in an array of strings

Time:11-16

How do I find a single character in a string that is in a string array? I need it to be switched with another letter. Given an array

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

I need to replace a single character in each word (let's say the letter 'l', and then changed to the letter 'x'), so that the array becomes

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

CodePudding user response:

You can do the task for example using the range based for loop.

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

Instead of the inner loop you can use the standard algorithm std::replace. For example

#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';
}

The program output is

hexxo my name is xukas

Or instead of the both loops you could use the standard algorithm std::for_each like

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

CodePudding user response:

With range views and algorithms, you can simply do

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

Here's a demo.

  • Related