【问题标题】:In need of a C++ function that breaks a line into strings that include only numbers/letters需要一个 C++ 函数,将一行分成仅包含数字/字母的字符串
【发布时间】:2014-02-17 00:55:32
【问题描述】:

我想知道如何将一行分成仅包含数字和字母(无标点符号)的字符串。我在网上看到过可以做到这一点的公式,但省略了有关如何省略标点符号的说明。

【问题讨论】:

  • 您能否提供问题中所指行的示例?

标签: c++ string line break


【解决方案1】:

您可以使用<cctype> 中的函数来测试您的角色。在您的情况下,您可能想使用isalnum

【讨论】:

  • 如果我把我的词当作类型字符串,是否可以这样做,或者我只能用 char * 这样做?
  • 当您使用string::operator[] 时,您会得到一个字符,就像您使用char* 一样。简短的回答是“是”。
  • @Michformer std::isalnum 仅适用于单个字符,因此这两个选项都是可行的。
  • 另外,它需要是一个一次处理(即返回)一个单词的函数
  • 当我从字符串中提取一个字符时,我可以将它放在一个数组或其他东西中(char * extract[])吗?
【解决方案2】:

这就是擦除删除成语派上用场的地方。编辑:不需要 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;
}

【讨论】:

    【解决方案3】:

    详细信息会根据您想要实现的确切目标而有所不同,但让我们假设有一组您想要的字符,而所有其他字符都是不需要的,输出将是输入中所有连续的想要字符组.那么伪代码将是:

    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
    

    很抱歉伪代码,但这是我能做的最好的,不知道你正在使用什么字符串类。

    【讨论】:

    • 我使用的是字符串类型。
    • 我应该这样认为。我更熟悉 MFC CString,这对我来说越来越痛苦。好吧,例如,您可以使用 find_first_not_of 查找不在“想要”列表中的第一个字符,擦除以从字符串中删除字符等等......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-30
    • 1970-01-01
    • 2021-01-31
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多