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

How to identify string is containing only number?

本文关键字:字符串 包含 数字 识别 何识别      更新时间:2023-10-16

如何只打印字符串中的文本?我只想从打印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的成员函数。

其次,问题的标题与您所问的问题与代码不匹配。不过,我会设法处理这两个问题。(


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

您可以简单地打印字符串中的每个元素(即chars(,如果它是一个字母表,同时对其进行迭代。检查可以使用标题<cctype>中名为std::isalpha的标准函数来完成(请参阅此处的实际示例(

#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(需要包括标头<algorithm>(以及std::isdigit(来自<cctype>标头(来实现此目的(请在线查看实时示例(

#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 numbersn";
else 
std::cout << "String contains non-numbers as welln";
}

输出

String contains non-numbers as well

您可以使用std::stringfind_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"

在这样的场景中使用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';
}