如何区分数字和字符串

时间:2016-03-22 09:09:18

标签: java string integer

我有一个字符串

String s="Raymond scored 2 centuries at an average of 34 in 3 innings.";

我需要找到字符串中只有数字的总和,而不会遇到任何异常。这里的总和应该是2 + 34 + 3 = 39。如何让编译器理解String和Integer之间的区别。

7 个答案:

答案 0 :(得分:5)

您应该按空格(或通过正则表达式,从您的问题中不清楚)将输入字符串拆分为String标记数组,然后遍历此数组。如果Integer.parseInt(token)调用未产生NumberFormatException异常,则返回一个整数,您应将其添加到numbers列表中以进行进一步处理(或立即添加到总和)

String inputString = "Raymond scored 2 centuries at an average of 34 in 3 innings.";
String[] stringArray = inputString.split(" ");//may change to any other splitter regex
List<Integer> numbers = new ArrayList<>();
for (String str : sArr) {
   try {
       numbers.add(Integer.parseInt(str)); //or may add to the sum of integers here
   } catch (NumberFormatException e){
        System.out.println(e);
   }
}
//todo any logic you want with the list of integers

答案 1 :(得分:1)

您应该使用正则表达式拆分字符串。将在所有非数字字符之间进行拆分。以下是示例代码:

    String text = "there are 3 ways 2 win 5 games";
    String[] numbers = text.split("\\D+");
    int sum = 0;
    for (String number : numbers) {
        try {
            sum += Integer.parseInt(number);
        } catch (Exception ex) {
            //not an integer number
        }
    }
    System.out.println(sum);

答案 2 :(得分:1)

public void sumOfExtractedNumbersFromString(){
        int sum=0;
        String value="hjhhjhhj11111 2ssasasa32sas6767676776767saa4sasas";
        String[] num = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" };
        for(char c : value.toCharArray())        
        {
            for (int j = 0; j < num.length; j++) {
                String val=Character.toString(c);
                if (val.equals(num[j])) {
                    sum=sum+Integer.parseInt(val);
                }
            }
        }
        System.out.println("Sum"+sum);`
    }

答案 3 :(得分:1)

 public class MyClass {    
      public int addition(String str){
           String[] splitString = str.split(" "); 
           // The output of the obove line is given below but now if this string contain 
           //'centuries12' then we need to split the integer from array of string.
           //[Raymond, scored, 2, centuries12, at, an, average, of, 34, in, 3, innings]

           String[] splitNumberFromSplitString= str.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
           // The output of above line is given below this regular exp split the integer
           // number from String like 'centuries12'
           // [Raymond scored,2,centuries,12, at an average of,34,  in , 3,  innings]     

           int sum=0;

           for (String number : splitNumberFromSplitString) {
               if(StringUtils.isNumeric(number)){
                  sum += Integer.parseInt(number);
               }
            }        
            return sum;
        }


        public static void main(String args[]) {
            String str = "Raymond scored 2 centuries at an average of 34 in 3 innings";
            MyClass obj = new MyClass();
            int result  = obj.addition(str);
            System.out.println("Addition of Numbers is:"+ result);
        }

    }

输出

Addition of Numbers is:39

答案 4 :(得分:0)

有多种方法可以解决您的问题。我假设你只是在寻找整数(否则每个解决方案都可能适用于寻找浮动数字)。

  1. 使用regular expressions

    public static int sumByRegEx(final String input) {
        final Pattern nrPattern = Pattern.compile("\\d+");
        final Matcher m = nrPattern.matcher(input);
    
        int sum = 0;
        while (m.find()) {
            sum += Integer.valueOf(m.group(0));
        }
    
        return sum;
    }
    
  2. 使用Scanner

    public static int sumByScanner(final String input) {
        final Scanner scanner = new Scanner(input);
    
        int sum = 0;
        while (scanner.hasNext()) {
            if (scanner.hasNextInt()) {
                sum += scanner.nextInt();
            } else {
                scanner.next();
            }
        }
        scanner.close();
    
        return sum;
    }
    
  3. 使用String方法:

    public static int sumByString(final String input) {
        return Stream.of(input.split("\\s+"))
                .mapToInt(s -> {
                    try {
                        return Integer.valueOf(s);
                    } catch (final NumberFormatException e) {
                        return 0;
                    }
                }).sum();
    }
    
  4. 所有案例都会返回正确的结果(只要未通过null):

    public static void main(final String[] args) {
        final String sample = "Raymond scored 2 centuries at an average of 34 in 3 innings.";
    
        // get some 39:
        System.out.println(sumByRegEx(sample));
        System.out.println(sumByScanner(sample));
        System.out.println(sumByString(sample));
    
        // get some 0:
        System.out.println(sumByRegEx(""));
        System.out.println(sumByScanner(""));
        System.out.println(sumByString(""));
    
        // some "bad" examples, RegEx => 10, Scanner => 0, String => 0
        System.out.println(sumByRegEx("The soccer team is playing a 4-3-3 formation."));
        System.out.println(sumByScanner("The soccer team is playing a 4-3-3 formation."));
        System.out.println(sumByString("The soccer team is playing a 4-3-3 formation."));
    }
    

答案 5 :(得分:0)

我认为你应该写一个不同的函数来检查它是否是一个数字或者不是好的做法:

public class SumOfIntegersInString {
public static void main(String[] args) throws ClassNotFoundException {
String s = "Raymond scored 2 centuries at an average of 34 in 3 innings.";
String[] splits= s.split(" ");
System.out.println(splits.length);
int sum = 0; 
for (int j=0;j<splits.length;j++){
if (isNumber(splits[j]) == true){
int number = Integer.parseInt(splits[j]);
sum = sum+number;
    };
  };
System.out.println(sum);
};

public static boolean isNumber(String string) {
    try {
        Integer.parseInt(string);
    } catch (Exception e) {
        return false;
    }
    return true;
  }
}

答案 6 :(得分:0)

没有花哨的技巧:检查每个字符是否为数字,如果是,则解析/添加它。

public static void SumString (string s)
{
    int sum = 0, length = s.length();
    for (int i = 0; i < length; i++)
    {
         char c = s.charAt(i);
         if (Character.isDigit(c))
             sum += Integer.parseInt(c);
    }
    return sum;
}