`
jordan_micle
  • 浏览: 240254 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

JAVA判断字符串是否整数

阅读更多

1. 使用类型转换判断

 

try { 
	String str="123abc"; 
	//把字符串强制转换为数字 
	int num=Integer.valueOf(str);
	//如果是数字,返回True 
	return true;
} catch (Exception e) {
	//如果抛出异常,返回False 
	return false;
}

 

 

2. 使用正则表达式判断

 

String str = "abc123"; 
boolean isNum = str.matches("[0-9]+"); 
//+表示1个或多个(如"3"或"225"),*表示0个或多个([0-9]*)(如""或"1"或"22"),?表示0个或1个([0-9]?)(如""或"7") 

 

3. 使用Pattern类和Matcher

 

String str = "123"; 
Pattern pattern = Pattern.compile("[0-9]+"); 
Matcher matcher = pattern.matcher((CharSequence) str); 
boolean result = matcher.matches(); 
if (result) { 
	System.out.println("true"); 
} else { 
	System.out.println("false"); 
}

 

4. 使用Character.isDigit(char)判断

 

String str = "123abc"; 
if (!"".equals(str)) { 
	//把字符串转换为字符数组
	char num[] = str.toCharArray(); 
	//使用StringBuffer类,把非数字放到title中
	StringBuffer title = new StringBuffer(); 
	//把数字放到hire中
	StringBuffer hire = new StringBuffer(); 

	for (int i = 0; i < num.length; i++) { 
		// 判断输入的数字是否为数字还是字符 
		// 把字符串转换为字符,再调用Character.isDigit(char)方法判断是否是数字
		if (Character.isDigit(num[i])) { 
			hire.append(num[i]);// 如果输入的是数字,把它赋给hire 
		} else { 
			title.append(num[i]);// 如果输入的是字符,把它赋给title 
		} 
	} 
}

 

转自:http://hi.baidu.com/frjay/blog/item/71b9500a685ee433b1351da8.html

分享到:
评论
2 楼 solen 2014-06-28  
1、如何将字符串String转化为整数int
  int i = Integer.parseInt(str);
  int i = Integer.valueOf(my_str).intValue();
   注: 字串转成Double, Float, Long的方法大同小异。
2、如何将字符串String转化为Integer
   Integer integer=Integer.valueOf(i)
3、如何将整数 int 转换成字串 String?
答:有三种方法:
  String s = String.valueOf(i);
  String s = Integer.toString(i);
  String s = "" + i;
注:Double, Float, Long 转成字串的方法大同小异。
4、如何将整数int转化为Integer
  Integer integer=new Integer(i)
5、如何将Integer转化为字符串String
   Integer integer=String()
6、如何将Integer转化为int
   int num=Integer.intValue()
7、如何将String转化为BigDecimal
   BigDecimal d_id=new BigDecimal(str)
1 楼 solen 2014-06-28  
a:for(int i=0;i<n;i++) { b:for(int j=0;j<n;j++) { if(n=0) { break b; } }

相关推荐

Global site tag (gtag.js) - Google Analytics