#include <iostream>
#include <string>
std::string removeSpecialCharacters(const std::string& input) {
std::string output;
for (char c : input) {
// 检查字符是否为字母、数字或空格
if (isalnum(c) || c == ' ') {
output += c;
}
}
return output;
}
int main() {
std::string input = "Hello, World! 123";
std::string output = removeSpecialCharacters(input);
std::cout << "输入字符串: " << input << std::endl;
std::cout << "移除特殊字符后的字符串: " << output << std::endl;
return 0;
}
这段代码演示了如何移除字符串中的特殊字符。removeSpecialCharacters
函数接受一个字符串作为输入,并返回一个移除了特殊字符的新字符串。
函数遍历输入字符串的每个字符,并使用 isalnum
函数检查字符是否为字母或数字。如果字符是字母、数字或空格,则将其添加到输出字符串中。
在 main
函数中,我们使用示例字符串 “Hello, World! 123” 作为输入,并调用 removeSpecialCharacters
函数来获取移除特殊字符后的字符串。然后,我们将输入字符串和移除特殊字符后的字符串打印到控制台上。
输出结果如下:
输入字符串: Hello, World! 123
移除特殊字符后的字符串: Hello World 123
这样,我们成功移除了输入字符串中的特殊字符。你可以根据自己的需求修改和扩展这个函数,以满足不同的字符串处理需求。