一道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]"));
}
public static void main(String[] args) {
String str = "今天是2012人头,现147在事1月5号";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(str);
StringBuffer sb = new StringBuffer();
sb.append("[");
while(matcher.find()){
sb.append(matcher.group());
sb.append(",");
}
//删除最后一次添加上的,
sb.delete(sb.length() - 1, sb.length());
sb.append("]");
System.out.println(sb);
}
public static void main(String[] args) {
String str = "今天是2012人头,现147在事1月5号";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(str);
StringBuffer sb = new StringBuffer();
sb.append("[");
while(matcher.find()){
sb.append(matcher.group());
sb.append(",");
}
//删除最后一次添加上的,
sb.setCharAt(sb.length() - 1, ']');
System.out.println(sb);
}
System.out.println(Arrays.toString("今天是2012人头,现147在事1月5号".replaceAll("^\\D+", "").split("\\D+")));