替换字符串中的所有字符,但带有下划线的空格除外

时间:2015-11-06 04:22:43

标签: c++

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

这是一个刽子手任务。

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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

使用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;
}

答案 2 :(得分:1)

这是使用标准库算法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';
}
相关问题