如何识别字符串只包含数字
How to identify string is containing only number?
如何只打印字符串中的文本?我只想从打印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
的成员函数。
其次,问题的标题与您所问的问题与代码不匹配。不过,我会设法处理这两个问题。(
如何只打印字符串中的文本?
您可以简单地打印字符串中的每个元素(即char
s(,如果它是一个字母表,同时对其进行迭代。检查可以使用标题<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::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"
。
在这样的场景中使用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';
}
相关文章:
- 编译包含字符串的代码时遇到问题
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 一个函数,用于查找字符串1包含字符串2 c++的次数
- C++ 创建包含链表和字符串的对象的链接列表时出错
- C++-字符串是否包含一个带有简单循环的单词
- 编辑字符串以包含括号 c++ 之间的变量
- 使用提升元解析字符串解析包含的文件
- 当字符串包含 %2C 时,在 c++ 中不完整的 std::string
- C++ 检查 UTF8 字符串包含指定的字符
- 将文件作为字符串包含在内
- 为什么string.empty()在字符串包含一个值时评估为true
- boost::p rogram_option::store 在选项字符串包含混合语言字符时引发异常
- 在 c++ 中将字符串(包含字符和浮点数)转换为双精度
- 将字符串(包含数字)转换为整数并返回该整数
- 如果输入字符串包含"%",则vsntprintf_s崩溃
- 当一个字符串包含另一个字符串的一部分时比较字符串
- 如果字符串包含多个 ,如何在每25个换行符( )上分割字符串
- 输出字符串包含奇怪的字符
- 当字符串包含多个NUL字符时,如何获取c_str(用于发送)
- 乘法的字符串[包含整数],输出也存储在字符串中,如何