【发布时间】:2014-02-17 00:55:32
【问题描述】:
我想知道如何将一行分成仅包含数字和字母(无标点符号)的字符串。我在网上看到过可以做到这一点的公式,但省略了有关如何省略标点符号的说明。
【问题讨论】:
-
您能否提供问题中所指行的示例?
我想知道如何将一行分成仅包含数字和字母(无标点符号)的字符串。我在网上看到过可以做到这一点的公式,但省略了有关如何省略标点符号的说明。
【问题讨论】:
您可以使用<cctype> 中的函数来测试您的角色。在您的情况下,您可能想使用isalnum。
【讨论】:
string::operator[] 时,您会得到一个字符,就像您使用char* 一样。简短的回答是“是”。
std::isalnum 仅适用于单个字符,因此这两个选项都是可行的。
这就是擦除删除成语派上用场的地方。编辑:不需要 lambda。
#include <iostream>
#include <algorithm>
#include <cctype>
int main()
{
std::string s = "!%@T%abc";
s.erase(std::remove_if(s.begin(), s.end(), ispunct), s.end());
std::cout << s;
}
【讨论】:
详细信息会根据您想要实现的确切目标而有所不同,但让我们假设有一组您想要的字符,而所有其他字符都是不需要的,输出将是输入中所有连续的想要字符组.那么伪代码将是:
while input not empty
remove all unwanted characters from from of input string
find first unwanted character in input string
if not found
last output string is remains of input string
empty out input string
else
next output string is all chars before unwanted char
remove all the wanted chars we found from the input string
end
很抱歉伪代码,但这是我能做的最好的,不知道你正在使用什么字符串类。
【讨论】: