【问题标题】:How to identify string is containing only number?如何识别字符串只包含数字?
【发布时间】:2020-02-19 07:20:14
【问题描述】:

如何只打印字符串中的文本?我只想打印来自的abc。

string numtext = "abc123";

这里是完整的代码:

#include <stdio.h>

int main()
{
    string text = "abc123";

    if (text.matches("[a-zA-Z]") //get an error initialization makes integer from pointer without a cast
    {
        printf("%s", text);
    }
    getch();
}

我的字符串包含数字和字母,我只想打印字母。但我得到一个错误。我做错了什么?

【问题讨论】:

  • std::string 没有名为 matches 的成员,以防万一你不知道。
  • 一个非常粗略和昂贵的解决方案:try 将其转换为数字类型和catch 一个错误。
  • @JeJo 你是什么意思?意味着我的程序中缺少命名空间??

标签: c++ algorithm stdstring alphabet


【解决方案1】:

首先,对于这种情况,没有名为std::string::matchesavailable in the standard string library 的成员函数。

其次,问题的标题与您提出的问题与代码不匹配。但是,我会尝试同时处理这两个问题。 ;)


如何只打印字符串中的文本?

你可以简单地打印字符串中的每个元素(即char s),如果它是一个字母,同时迭代它。可以使用标头&lt;cctype&gt; 中名为std::isalpha 的标准函数来完成检查。 (See live example here)

#include <iostream>
#include <string>
#include <cctype> // std::isalpha

int main()
{
    std::string text = "abc123";

    for(const char character : text)
        if (std::isalpha(static_cast<unsigned char>(character)))
            std::cout << character;
}

输出:

abc

如何识别字符串只包含数字?

提供一个函数来检查字符串中的所有字符是否为数字。您可以为此使用标准算法std::all_of(需要包含标题&lt;algorithm&gt;)和std::isdigit(来自&lt;cctype&gt; 标题)。 (See live example online)

#include <iostream>
#include <string>
#include <algorithm> // std::all_of
#include <cctype>    // std::isdigit
#include <iterator>  // std::cbegin, std::cend()

bool contains_only_numbers(const std::string& str)
{
    return std::all_of(std::cbegin(str), std::cend(str),
        [](char charector) {return std::isdigit(static_cast<unsigned char>(charector)); });
}

int main()
{
    std::string text = "abc123";
    if (contains_only_numbers(text))
        std::cout << "String contains only numbers\n";
    else 
        std::cout << "String contains non-numbers as well\n";
}

输出:

String contains non-numbers as well

【讨论】:

【解决方案2】:

您可以使用std::string 的find_last_not_of 函数并创建一个substr

std::string numtext = "abc123"; 
size_t last_character = numtext.find_last_not_of("0123456789");
std::string output = numtext.substr(0, last_character + 1);

这个解决方案只是假设numtext 总是有text+num 的模式,这意味着像ab1c23 这样的东西会给出output = "ab"。

【讨论】:

    【解决方案3】:

    在这种情况下使用 C++ 标准 regex 是个好主意。你可以自定义很多。

    下面是一个简单的例子。

    #include <iostream>
    #include <regex>
    
    int main()
    {
    
        std::regex re("[a-zA-Z]+");
    
        std::cmatch m;//TO COLLECT THE OUTPUT
        std::regex_search("abc123",m,re);
    
    
       //PRINT THE RESULT 
        std::cout << m[0] << '\n';
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-26
      • 2022-08-07
      • 2011-11-30
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      相关资源
      最近更新 更多