`
jythoner
  • 浏览: 602086 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Java每日一题17

阅读更多
编写一个JAVA程序,从输入的一个字符串中提取出数字并组成一个整数

这道题肯定还有其他解法,比如用RE啥的,哪位朋友给个代码?
package test14;

import java.util.Scanner;

public class MyTest {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String line = "";
		StringBuffer sb = new StringBuffer();
		while (!(line = sc.next()).equals("exit")) {
			sb.append(line);
		}
		line = sb.toString();
		String result = "";
		for (int i = 0; i < line.length(); i++) {
			char ch = line.charAt(i);
			if (ch > 47 && ch < 58)
				result += ch;
		}
		System.out.println(result);

	}

}

7
4
分享到:
评论
9 楼 sxy707 2009-02-26  
String aa = "adfasdf3afd32adf323";
System.out.println(aa.replaceAll("\\D", ""));
8 楼 ramus 2009-02-26  
用正则一下就搞定
7 楼 mudong 2009-02-26  
不好意思  刚才没看到前面已经有人说了这种想法。
6 楼 mudong 2009-02-26  
text.replaceAll("\\D", "");
5 楼 dandy 2009-02-25  
貌似Scanner有更好的方法,试了下没成功。
4 楼 yf42 2009-02-25  
既然知道用正则了,就不要逐字符判断了啊

String strNum = str.replaceAll("\\D", "");

应该就ok了
3 楼 jythoner 2009-02-25  
xieye 写道

不知正则行不行

aben6658的就是正则
2 楼 xieye 2009-02-25  
不知正则行不行
1 楼 aben6448 2009-02-25  
public String getNum(String src){
		String re="^\\d";
		String result="";
		for (int i = 0; i < src.length(); i++) {
			if(String.valueOf(src.charAt(i)).matches(re)){
				result+=src.charAt(i);
			}
		}
		System.out.println(result);
		return result;
	}

相关推荐

Global site tag (gtag.js) - Google Analytics