package com.huifudianxia.interview;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 判断一个字符串是否为数值型字符串
 * @author yangjianzhou
 * 当是字符型字符串时返回1
 * 否则返回0
 *
 */
public class ProblemThree {

		public static void main(String[] args) {

			System.out.println(isNumber1("+001"));
			System.out.println(isNumber2("+1001"));

		}

		/**
		 * 使用字符串的matches方法
		 * @param s
		 * @return
		 */
		public static int isNumber1(String s){

			String regex = "^[1-9][0-9]*\\.[0-9]+$|^[1-9][0-9]*$|^0+\\.[0-9]+$";
			char c = s.charAt(0);
			boolean bool;
			if(c=='+'|c=='-'){
				bool = s.substring(1).matches(regex);
			}else{
				bool = s.matches(regex);
			}
			if(bool){
				return 1;
			}else{
				return 0;
			}
		}

		/**
		 * 使用Pattern和Matcher类的方法
		 * @param s
		 * @return
		 */
		public static int isNumber2(String s){

			String regex = "^[1-9][0-9]*\\.[0-9]+$|^[1-9][0-9]*$|^0+\\.[0-9]+$";
			Pattern pattern = Pattern.compile(regex);
			char c = s.charAt(0);
			if(c=='+'||c=='-'){
				s = s.substring(1);
			}
			Matcher matcher = pattern.matcher(s);
			boolean bool = matcher.matches();
			if(bool){
				return 1;
			}else{
				return 0;
			}
		}
}




运行结果:


0
1