Java中的AplhaNumeric字符串和计算

时间:2017-03-20 06:37:13

标签: java string eclipse logic alphanumeric

INPUT = Sd98TR2asd100

OUTPUT = 98 + 2 + 100 = 200

任何人都可以向我展示如何在不使用构建函数的情况下在java中解决这个问题的代码或逻辑

2 个答案:

答案 0 :(得分:0)

public static void main(String[] args) {
    String input = "Sd98TR2asd100";
    char[] chars = input.toCharArray();

    ArrayList<String> numbersAsString = new ArrayList<>();
    String toAdd = "";
    for(int i=0;i<chars.length;i++){
        if(chars[i]>='0' && chars[i]<='9'){
            toAdd += chars[i];
        }
        else{
            if(!toAdd.equals("")){
                numbersAsString.add(toAdd);
                toAdd = new String();
            }
        }
    }
    if(!toAdd.equals("")){
        numbersAsString.add(toAdd);
        toAdd = new String();
    }
    int sum = 0;
    String output = "";
    for(String string : numbersAsString){
        int num = Integer.parseInt(string);
        output += num +"+";
        sum +=num;
    }
    output = output.substring(0,output.length()-2);
    output += "="+ sum;
    System.out.println(output);
}

答案 1 :(得分:0)

 String myString ="Sd98TR2asd100";
 Pattern p = Pattern.compile("[0-9]+");
 Matcher m = p.matcher(myString);
 List list  = new ArrayList();
 while (m.find())
 {
   int n = Integer.parseInt(m.group());
    list.add(n);
   // append n to list
 }
 Integer sum = 0 ;
 Iterator itr = list.iterator();
 while(itr.hasNext())
 {
     sum += (Integer)itr.next();
 }
 System.out.println(sum);