将字符串中除空格外的所有字符替换为下划线

Replace all characters in a string except for spaces with underscores

本文关键字:字符 替换 下划线 字符串 空格      更新时间:2023-10-16

我一直在到处寻找答案,但我只能找到replace()函数。这很好,但我需要将字符串中的所有字符替换为分数不足的字符,除了空格,而不仅仅是一个特定的字符。

这是执行绞刑的任务。

此外,我没有提供任何代码,因为我不需要任何更改。我只需要语法和逻辑方面的帮助。

string str("hang man");
for (auto it = str.begin(); it != str.end(); ++it)
{
    if (*it!=' ')
    {
        *it = '_';
    }
}

使用C++标准库算法的简单示例:

#include <algorithm>
#include <iostream>
#include <string>
int main() 
{
    std::string str = " this is a   test;?";
    std::transform(str.begin(), str.end(), str.begin(),
        [](char c){return  c != ' ' ? '_' : ' ';});
    // this also does it
    /* std::for_each(str.begin(), str.end(), 
        [](char& c){if(c != ' ') c = '_';});
    */
    std::cout << str;
}

这里还有另一个使用标准库算法std::replace_if的替代方案。我喜欢这个解决方案,因为算法的名称很有意义,并且清楚地说明了它的作用。

#include <algorithm>
#include <iostream>
#include <string>
int main()
{
    std::string str = "I like turtles";
    std::replace_if(str.begin(), str.end(), [](char ch){ return ch != ' '; }, '_');
    std::cout << str << 'n';
}