Advertisement

判断输入的字符串是否为数字

阅读量:

目标

创建一个函数,使其接收一个字符串并判断该字符串是否为数字。

代码实现

C

复制代码
    #include <ctype.h>
    #include <stdlib.h>
    int isNumeric (const char * s)
    {
    if (s == NULL || *s == '\0' || isspace(*s))
      return 0;
    char * p;
    strtod (s, &p);
    return *p == '\0';
    }

C++

使用 stringstream

复制代码
    #include <sstream> // for istringstream
     
    using namespace std;
     
    bool isNumeric( const char* pszInput, int nNumberBase )
    {
    	istringstream iss( pszInput );
     
    	if ( nNumberBase == 10 )
    	{
    		double dTestSink;
    		iss >> dTestSink;
    	}
    	else if ( nNumberBase == 8 || nNumberBase == 16 )
    	{
    		int nTestSink;
    		iss >> ( ( nNumberBase == 8 ) ? oct : hex ) >> nTestSink;
    	}
    	else
    		return false;
     
    	// was any input successfully consumed/converted?
    	if ( ! iss )
    		return false;
     
    	// was all the input successfully consumed/converted?
    	return ( iss.rdbuf()->in_avail() == 0 );
    }

使用 find

复制代码
    bool isNumeric( const char* pszInput, int nNumberBase )
    {
    	string base = "0123456789ABCDEF";
    	string input = pszInput;
     
    	return (input.find_first_not_of(base.substr(0, nNumberBase)) == string::npos);
    }

使用 all_of (C++11)

复制代码
    bool isNumeric(const std::string& input) {
    return std::all_of(input.begin(), input.end(), ::isdigit);
    }

C#

复制代码
    //.Net 2.0+
    public static bool IsNumeric(string s)
    {
    double Result;
    return double.TryParse(s, out Result);  // TryParse routines were added in Framework version 2.0.
    }        
     
    string value = "123";
    if (IsNumeric(value)) 
    {
      // do something
    }
复制代码
    //.Net 1.0+
    public static bool IsNumeric(string s)
    {
      try
      {
    Double.Parse(s);
    return true;
      }
      catch
      {
    return false;
      }
    }

Go

复制代码
    import "strconv"
     
    func IsNumeric(s string) bool {
    _, err := strconv.ParseFloat(s, 64)
    return err == nil
    }

Java

复制代码
    public boolean isNumeric(String input) {
      try {
    Integer.parseInt(input);
    return true;
      }
      catch (NumberFormatException e) {
    // s is not numeric
    return false;
      }
    }

以上方式因为异常处理有巨大的性能损耗,可用以下四种方式代替。

方式一

检查字符串中的每个字符,此方式只适用于整数。

复制代码
    private static final boolean isNumeric(final String s) {
      if (s == null || s.isEmpty()) return false;
      for (int x = 0; x < s.length(); x++) {
    final char c = s.charAt(x);
    if (x == 0 && (c == '-')) continue;  // negative
    if ((c >= '0') && (c <= '9')) continue;  // 0 - 9
    return false; // invalid
      }
      return true; // valid
    }

方式二

使用正则表达式(推荐)。

复制代码
    public static boolean isNumeric(String inputData) {
      return inputData.matches("[-+]?\ d+(\ .\ d+)?");
    }

方式三

采用Java中的java.text.NumberFormat$PositionTag类中的位置解析器(更为可靠的一种解决方案)。 若在解析完成后发现该位置位于字符串末尾,则表明整个字符串仅包含一个数字。

复制代码
    public static boolean isNumeric(String inputData) {
      NumberFormat formatter = NumberFormat.getInstance();
      ParsePosition pos = new ParsePosition(0);
      formatter.parse(inputData, pos);
      return inputData.length() == pos.getIndex();
    }

方式四

使用java.util.Scanner。

复制代码
    public static boolean isNumeric(String inputData) {
      Scanner sc = new Scanner(inputData);
      return sc.hasNextInt();
    }

JavaScript

复制代码
    function isNumeric(n) {
      return !isNaN(parseFloat(n)) && isFinite(n);
    }
    var value = "123.45e7"; // Assign string literal to value
    if (isNumeric(value)) {
      // value is a number
    }
    //Or, in web browser in address field:
    //  javascript:function isNumeric(n) {return !isNaN(parseFloat(n)) && isFinite(n);}; value="123.45e4"; if(isNumeric(value)) {alert('numeric')} else {alert('non-numeric')}

Kotlin

复制代码
    // version 1.1
     
    fun isNumeric(input: String): Boolean =
    try {
        input.toDouble()
        true
    } catch(e: NumberFormatException) {
        false
    }
     
    fun main(args: Array<String>) {
    val inputs = arrayOf("152", "-3.1415926", "Foo123", "-0", "456bar", "1.0E10")
    for (input in inputs) println("$input is ${if (isNumeric(input)) "numeric" else "not numeric"}")
    }

输出:

复制代码
    152 is numeric
    -3.1415926 is numeric
    Foo123 is not numeric
    -0 is numeric
    456bar is not numeric
    1.0E10 is numeric

PHP

复制代码
    <?php
    $string = '123';
    if(is_numeric(trim($string))) {
    }
    ?>

Python

简单形式(整数/浮点数)

复制代码
    def is_numeric(s):
    try:
        float(s)
        return True
    except (ValueError, TypeError):
        return False
     
    is_numeric('123.0')

更简化(整数)

复制代码
    '123'.isdigit()

一般形式(二进制/十进制/十六进制/数字文本)

复制代码
    def is_numeric(literal):
    """Return whether a literal can be parsed as a numeric value"""
    castings = [int, float, complex,
        lambda s: int(s,2),  #binary
        lambda s: int(s,8),  #octal
        lambda s: int(s,16)] #hex
    for cast in castings:
        try:
            cast(literal)
            return True
        except ValueError:
            pass
    return False

Ruby

复制代码
    def is_numeric?(s)
      begin
    Float(s)
      rescue
    false # not numeric
      else
    true # numeric
      end
    end

更紧凑的形式

复制代码
    def is_numeric?(s)
    !!Float(s) rescue false
    end

全部评论 (0)

还没有任何评论哟~