如何在字符串数组中的字符串中找到单个字符?我需要它与另一个字母切换。给定一个数组
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/