문자 갯수 세기



토큰이 몇개 들었는지 세는 메소드
package ch12;

public class LibCountCharacter {
	int count(String str, String token) {
		return count(str, token, 0);
	}

	int count(String str, String token, int pos) {
		int tempPos= str.indexOf(token, pos); // 찾은 인덱스 번호 반환indexOf(찾으려는 문자열,
												// pos - 찾기 시작할 위치 )
				
		if (tempPos == -1) {
			return 0;
		}
		return count(str, token, tempPos + 1) + 1;
	}
}

사용 방법
package ch12;

public class ExerciseString2 {

	public static void main(String[] args) {
		
		String str = "동해물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라 만세 ";
		
		LibCountCharacter counter = new LibCountCharacter();
		int countNum = counter.count(str, " ");
		
		int[] tokenIdx = new int[countNum];
		int j=0;
		for (int i = 0; i < str.length(); i++) {
			if(i == str.indexOf(" ",i)){
				tokenIdx[j] = i;
				j++;
			}
		}
		for (int k = 0; k < tokenIdx.length; k++) {
			
			System.out.println(str.substring(0, tokenIdx[k]));
			
		}
	}
}