求字符串里面数字之和

97 阅读1分钟

无意看到别人面试问了很简单的问题,求字符串里面数字之和,所以自己来实现下。

例子:

比如字符串:aaaa13sseui9ddu78ff4sss

里面的字符串数字是13、9、78、4 得到的和为104

代码如下:

package com.sangfor.tree;

public class SumByString {
	
	public static int sumByString1(String s) {
		int result = 0;
		String newString = "";
		int count = 0;
		if (s == "" || s == null) {
			return 0;
		}
		char[] chars = s.toCharArray();
		for (char c : chars) {
			if ('0' <= c && c <='9') {
				newString += c;
				count = 0; 
			} else {
				if (count == 0) {
					newString += 'b';
					count++;
				}
			}
		}
		String[] charsNum = newString.split("b");
		for (String str:charsNum) {
			if (str.length() > 0) {
				result += Integer.parseInt(str);
			}
		}
		return result;
		
	}
	
	public static int