文字列の数値を分離して加算

1294 ワード


import java.util.StringTokenizer;

import org.junit.Test;

public class MyTest {
	
	String str = "A4b54e85a96sd5sddd113";
	
	@Test
	public void tstDigit(){
		
		
		StringBuilder sb = new StringBuilder(str);
		int len = sb.length();
		for(int i=0;i<len;i++){
			char ch = str.charAt(i);
			if(!Character.isDigit(ch)){
				sb.replace(i, i+1, "|");
			}
		}
		
		System.out.println(str);
		System.out.println(sb.toString());
		
		String[] digits = sb.toString().split("\\|");
		int total = 0;
		for(String s : digits){
			if(s != null && !"".equals(s)){
				System.out.println(s);
				total = total + Integer.parseInt(s);
			}
		}
		System.out.println(total);
	}
	
	@Test
	public void tstDigit2(){
		final String delim = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
		StringTokenizer st = new StringTokenizer(str,delim);
		int count = 0;
		while(st.hasMoreTokens()){
			count += Integer.parseInt(st.nextToken());
		}
		System.out.println(count);
	}

}