登錄 |創建賬號 |找回密碼
查看: 92|回復: 0

[通用] 检测字符串是否为数字

[複製鏈接]

23

主題

6

回帖

130

積分

管理員

Rank: 9Rank: 9Rank: 9

積分
130
發表於 2024-4-2 16:36:00 | 顯示全部樓層 |閱讀模式
在C++中,判断一个字符串是否全由数字组成可以通过类似的方法实现,但可以利用C++标准库中的功能来简化这一过程。一个常见的方法是使用std::all_of算法,结合std::isdigit函数和C++的lambda表达式。这种方法不仅简洁,而且充分利用了C++的STL(标准模板库)。
首先,需要包含几个头文件:<cctype>用于std::isdigit函数,<algorithm>用于std::all_of算法,以及<string>用于处理std::string类型的字符串。
下面是一个示例代码:
  1. #include <iostream>
  2. #include <cctype>      // 对于 std::isdigit
  3. #include <algorithm>   // 对于 std::all_of
  4. #include <string>      // 对于 std::string

  5. // 函数用于判断字符串是否全由数字组成
  6. bool isNumeric(const std::string& str) {
  7.     return !str.empty() && std::all_of(str.begin(), str.end(), [](unsigned char c) { return std::isdigit(c); });
  8. }

  9. int main() {
  10.     std::string age = "28";
  11.     if (isNumeric(age)) {
  12.         std::cout << age << " 是一个数字字符串。" << std::endl;
  13.     } else {
  14.         std::cout << age << " 不是一个数字字符串。" << std::endl;
  15.     }

  16.     return 0;
  17. }
複製代碼
在这个示例中,isNumeric函数检查字符串str是否不为空,然后使用std::all_of算法遍历字符串中的所有字符。对于字符串中的每个字符,它使用一个lambda表达式作为谓词,这个lambda表达式调用std::isdigit来判断字符是否为数字。如果所有的字符都通过了这个检查,std::all_of将返回true,否则返回false。
注意,std::isdigit需要一个int类型的参数,但是标准库中的字符可能是有符号或无符号的,这取决于编译器。因此,在lambda表达式中,字符被显式地转换为unsigned char,然后再被传递给std::isdigit,以避免潜在的负值导致的问题。

回復

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 創建賬號

本版積分規則

Archiver|手機版|小黑屋|九派社區 ( 苏ICP备07501547号-12 )

GMT+8, 2024-5-21 10:55 , Processed in 0.041945 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回復 返回頂部 返回列表