【问题标题】:How to check if a string contains characters or numbers C++ and C#如何检查字符串是否包含字符或数字 C++ 和 C#
【发布时间】:2011-07-22 07:37:52
【问题描述】:

我有可能的变量值如下“Name_1”和“1535”。

我想要一个 C++ 或 C# 中的库函数来确定变量值是“1535”(它是数字)还是“Name_1”(它是一个名称)。

告诉我有哪些可用的功能?

【问题讨论】:

  • 你有数字范围吗? “-2”是一个可能出现的值吗?是“3.1415”吗?是“3E-4”吗?
  • @Rahul,如果您发现某人的答案是正确的,请将其标记为答案。将您的接受率视为 0% 会使其他人不愿意回答您的问题。

标签: c# c++ string


【解决方案1】:

假设可以将任何非整数字符串视为“字符”:

Int32.TryParse:

String variable = "1234";
Integer dummyresult
if Int32.TryParse(variable,dummyresult)
{
    // variable is numeric
}
else
{
    // variable is not numeric
}

【讨论】:

    【解决方案2】:
    string s = "1235";
    
    Console.WriteLine("String is numeric: " + Regex.IsMatch(s, "^[0-9]+$"));
    

    【讨论】:

      【解决方案3】:

      在 C++ 中,boost::lexical_cast 会派上用场:

      #include <boost/lexical_cast.hpp>
      #include <iostream>
      
      bool IsNumber(const char *s) {
        using boost::lexical_cast;
      
        try {
          boost::lexical_cast<int>(s);
          return true;
        } catch (std::bad_cast&) {
          return false;
        }
      }
      
      int main(int ac, char **av) {
        std::cout << av[1] << ": " << std::boolalpha << IsNumber(av[1]) << "\n";
      }
      


      编辑:如果您无法使用 Boost,请尝试以下操作:
      bool IsNumber2(const char *s) {
      
        std::istringstream stream(s);
        stream.unsetf(std::ios::skipws);
      
        int i;
        if( (stream >> i) && stream.eof() )
          return true;
        return false;
      }
      

      【讨论】:

        猜你喜欢
        • 2012-06-27
        • 2015-02-07
        • 2021-12-20
        • 2012-02-11
        • 2011-01-21
        • 1970-01-01
        • 2018-10-03
        • 2015-12-29
        • 2021-06-12
        相关资源
        最近更新 更多