如何在字符串数组中找到一个单个字符并将其替换为另一个字符? 给定一个数组
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' );
} );
std::string::find
查找和替换你想要改变的字符。 - NathanOliver