将字符串中除空格外的所有字符替换为下划线
Replace all characters in a string except for spaces with underscores
我一直在到处寻找答案,但我只能找到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';
}
相关文章:
- 生成随机.txt文件,10行,10列。充满随机:"*"、"#"、"@"。然后将随机字符替换为'P'
- 我想仅使用递归将字符"a"替换为字符"z"
- 将一个字符替换为字符串中更多数量的字符,而不删除C++中的其他字母
- 如何将像'A'这样的单个字符替换为类似"10"?
- Qt:文件名中的非 ASCII 字符替换为"?"
- 我无法用字符替换重复的数字"a"
- QtLineEdit 占位符:如何让用户在插入模式下将字符 1 替换为 1
- 将一个特定字符替换为正则表达式匹配中的另一个字符
- 如何将所有出现的字符替换为给定的字符串
- 将一个数组到另一个数组的字符替换为字符串
- C++ 字符串,用于删除字符'b'并将字符'a'替换为两个'd'的构建函数
- 将字符串中的所有非 ASCII 字符替换为其等效的 ASCII
- 将utf8编码的字符串转换为本地8位编码的字符串,并将无法确定的字符替换为空白
- C++-用非ascii字符替换文件中的特殊字符
- 将字符串中的 č,š,ć 等字符替换为其 html 代码C++
- 用连字符替换字符串中的文本
- 用不同字符替换单词的代码
- 将空白字符替换为 %20 的字符串,忽略所有尾随空格
- 将部分字符*替换为较小的字符*
- 将字符串中的字符替换为某个字符串