在 C++ 中从用户输入中剥离/删除符号
到目前为止,我得到的信息如下:
string stripSymbols(string str) {
int stringSize = strlen(str.c_str());
for (int i = 0; i < stringSize; i++)
if (str[i] == 0x46)
str[i] = 0x32;
return str;
}
我知道 ascii 代码可能是错误的。这是问题的一部分。但一旦我弄清楚了这些,我就想我可以在这里为每个符号放置一个开关,用一个空格替换每个符号。
或者更好的是,我可以在 for 循环中添加一个 for 循环,循环遍历一串符号,并将与用户输入匹配的任何符号替换为空白。
我有几个想法,但我想知道是否有更有效的方法来做到这一点。
更新 1:
这段代码看起来更好一些并且可以工作:
string stripSymbols(string str) {
int stringSize = str.size();
for (int i = 0; i < stringSize; i++)
if (str[i] == '.')
str[i] = ' ';
return str;
}
但是回复提供了更有效的解决方案。
更新 2:
受 Kerrek SB 回复启发的解决方案:
char symbols [] = {'!', '?', ',', '\'', '.'};
int symbols_size = sizeof(symbols) / sizeof(char);
for (int j = 0; j < symbols_size; j++)
replace(str.begin(), str.end(), symbols[j], ' ');
Here's what I have so far:
string stripSymbols(string str) {
int stringSize = strlen(str.c_str());
for (int i = 0; i < stringSize; i++)
if (str[i] == 0x46)
str[i] = 0x32;
return str;
}
I know the ascii codes are probably wrong. That's part of the problem. But once I figure those out, I was thinking I could maybe put a switch in here for each symbol that would replace each symbol with an empty space.
Or better yet, I could have a for loop in my for loop that loops through a string of symbols and replaces any that match with the user's input with an empty space.
I have a couple ideas, but I was wondering if there was a more efficient way of doing this.
Update 1:
This code looks a little better and works:
string stripSymbols(string str) {
int stringSize = str.size();
for (int i = 0; i < stringSize; i++)
if (str[i] == '.')
str[i] = ' ';
return str;
}
But the replies offer a more efficient solution.
Update 2:
Solution inspired by Kerrek SB's reply:
char symbols [] = {'!', '?', ',', '\'', '.'};
int symbols_size = sizeof(symbols) / sizeof(char);
for (int j = 0; j < symbols_size; j++)
replace(str.begin(), str.end(), symbols[j], ' ');
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您想用空格替换任何非字母数字字符:
If you want to replace any non-alphanumeric character with a space:
如果我想要一个强大的解决方案,我可能会使用
boost::regex_replace
:文档
If I were going for a robust solution I'd probably just use
boost::regex_replace
:Documentation
看一下
string::find
和string::replace
方法。Take a look at
string::find
andstring::replace
methods.我会尝试这样的事情:
您甚至可以在原始上下文中执行此操作,不需要单独的函数。您需要
#include
。I'd try something like this:
You can do this in the original context even, no need for a separate function. You need to
#include <algorithm>
.您是否希望从
std::string
中删除/替换特定字符的每个实例?如果是这样,请参阅这些类似的问题:如何替换所有字符串中出现某个字符?
从 std::string 中删除空格in C++
只需使用答案中显示的概念即可满足您自己的目标。
Are you wishing to just remove/replace every instance of a specific character from a
std::string
? If so, see these similar questions:How to replace all occurrences of a character in string?
Remove spaces from std::string in C++
And just use the concepts displayed in the answers to suit your own goals.