[Java] 6.2.8 String 클래스 멤버 중에 구분자로 문자열 잘라내는 메서드

프로그래밍에서 문자열 데이터를 사용할 때 필요에 의해 구성하는 부분 문자열로 나누어 분석해야 할 때가 생깁니다. 예를 들어 하나의 문자열에 몇 개의 단어로 구성하고 있고 빈도수를 확인하고자 한다면 원본 문자열을 공백으로 구분하여 단어마다 별도의 문자열 개체로 만든 후에 빈도수를 확인하는 것이 효과적일 것입니다.

Java 언어의 String 클래스는 split 멤버 메서드를 제공하여 구분자를 기준으로 원본 문자열을 분할할 수 있습니다.

String[] split(String str)
String[] split(String str, int limit)

만약 원본 문자열 origin에 특정 word가 몇 개 있는지 파악하려고 한다면 먼저 origin을 공백을 기준으로 구성 단어들로 구성한 문자열 배열을 만들어야 할 것입니다. 이 때 split 메서드를 사용합니다.

String[] sarr = origin.split(" ");

그리고 sarr의 원소들과 word를 equals 메서드를 이용하여 참일 때 빈도수를 카운팅하면 origin에 word가 몇 개 있는지 파악할 수 있습니다.

int len = sarr.length;
int count = 0;
for(int i = 0; i<len; i++){
	if(word.equals(sarr[i])){
		count++;
	}
}

다음은 origin에 word가 몇 개 있는지 파악하는 예제 코드입니다.

//원본 문자열에 특정 단어가 몇 개 있는지 분석 예
import java.util.Scanner;
public class Program {
	static Scanner scanner = new Scanner(System.in); 
	public static void main(String[] args){
		String origin = "";
		System.out.println("원본 문자열 입력:");
		origin = scanner.nextLine();
		
		String word="";
		System.out.println("검색할 단어 입력:");
		word = scanner.next();
		
		System.out.println("원본:"+origin);
		System.out.println("검색할 단어:"+word);
		
		String[] sarr = origin.split(" ");
		
		int len = sarr.length;
		int count = 0;
		for(int i = 0; i<len; i++){
			if(word.equals(sarr[i])){
				count++;
			}
		}
		System.out.println("빈도수:"+count);
	}
}

실행 결과

원본 문자열 입력:
My name is eh jang. My dream is to be a education engineer. 
검색할 단어 입력:
My
원본:My name is eh jang. My dream is to be a education engineer.
검색할 단어:My
빈도수:2