日期:2014-05-20  浏览次数:20788 次

一道java编程题求高手指点啊!
有一个字符串str="今天是2012人头,现147在事1月5号";要求只打印出字符串里的数字,写一个算法求打印结果为[2012,147,1,5]; 
------最佳解决方案--------------------
public class test {

public static void main(String[] args) {
String str="今天是2012人头,现147在事1月5号";
char[] buf=str.toCharArray();
String sub="";
if(buf[0]<='9'&&buf[0]>='0')
sub+=buf[0];
for(int i=1;i<buf.length;i++)
{
if(buf[i]<='9'&&buf[i]>='0')
sub+=buf[i];
else if(buf[i-1]<='9'&&buf[i-1]>='0')
sub+=",";
}
System.out.print(sub);
}

}
Lz满意不
------其他解决方案--------------------
public static void main(String[] args) {
String str = "今天是2012人头,现147在事1月5号";
char c ;
int length = str.length();
System.out.println(length);
String str1 = "";
List list = new ArrayList();
for(int i = 0;i<length;i++){
System.out.println(i);
c = str.charAt(i);

if(c>=48&&c<=58){
str1 += c;
if(str.charAt(i+1)>=48&&str.charAt(i+1)<=58){
continue;
}
list.add(str1);
str1 = "";
}

}
System.out.println(list);
}
------其他解决方案--------------------
System.out.println("输入一个字符串:");
  Scanner scanner = new Scanner(System.in); 
  StringBuffer sb=new StringBuffer();
  String line = scanner.nextLine(); 
  char a[]=line.toCharArray();
  System.out.println("打印出其中所有的数字:"); 
  for (int i = 0; i < a.length; i++) 
  { 
    if(Character.isDigit(a[i]))
     sb.append(a[i]);    
  } 
  System.out.println(sb);

------其他解决方案--------------------
public static void main(String[] args) {
String str = "今天是2012人头,现147在事1月5号";
char c ;
int length = str.length();
System.out.println(length);
String str1 = "";
List list = new ArrayList();
for(int i = 0;i<length;i++){
System.out.println(i);
c = str.charAt(i);

if(c>=48&&c<=58){
str1 += c;
if(str.charAt(i+1)>=48&&str.charAt(i+1)<=58){
continue;
}
list.add(str1);
str1 = "";
}

}
System.out.println(list);

------其他解决方案--------------------
为什么又是这个题..我记得昨天才回答过一次基本上一样的

public static void main(String[] args) {
System.out.println("今天是2012人头,现147在事1月5号".replaceAll("\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)\\D+", "[$1,$2,$3,$4]"));
}

------其他解决方案--------------------
引用:
为什么又是这个题..我记得昨天才回答过一次基本上一样的
Java code?1234public static void main(String[] args) {        System.out.println("今天是2012人头,现147在事1月5号".replaceAll("\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)\\……