Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

자바에서 모음으로 시작하는 단어만 추출하는 방법 – split()과 charAt() 활용하기

텍스트에서 모음(a, e, i, o, u)으로 시작하는 단어를 찾고 싶다면, 문자열을 단어 단위로 분리한 뒤 각 단어의 첫 글자를 검사하는 방식으로 손쉽게 구현할 수 있습니다. 전체 과정은 다음과 같습니다.

  • String 클래스의 split() 메서드를 사용해 주어진 문자열을 공백을 기준으로 분리하여 문자열 배열로 만듭니다.
  • for 루프를 통해 배열에 담긴 각 단어를 하나씩 순회합니다.
  • charAt() 메서드로 각 단어의 첫 번째 문자를 가져옵니다.
  • if 문으로 해당 문자가 모음 중 하나와 일치하는지 확인하고, 일치한다면 그 단어를 출력합니다.

예제

다음과 같은 내용을 담고 있는 텍스트 파일(sample.txt)이 있다고 가정해 보겠습니다.

Tutorials Point originated from the idea that there exists a class of readers who respond better to 
on-line content and prefer to learn new skills at their own pace from the comforts of their drawing rooms.

아래 자바 프로그램은 이 파일을 읽어 들인 후, 모음으로 시작하는 모든 단어를 찾아 출력합니다.

import java.io.File;
import java.util.Scanner;
public class WordsStartWithVowel {
    public static String fileToString(String filePath) throws Exception {
        Scanner sc = new Scanner(new File(filePath));
        StringBuffer sb = new StringBuffer();
        String input = new String();
        while (sc.hasNextLine()) {
            input = sc.nextLine();
            sb.append(input);
        }
        return sb.toString();
    }
    public static void main(String args[]) throws Exception {
        String str = fileToString("D:\\sample.txt");
        String words[] = str.split(" ");
        for(int i = 0; i < words.length; i++) {
            char ch = words[i].charAt(0);
            if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                System.out.println(words[i]);
            }
        }
    }
}

코드 설명

fileToString() 메서드는 Scanner를 이용해 파일을 한 줄씩 읽어 StringBuffer에 누적한 뒤, 전체 내용을 하나의 문자열로 반환합니다. 이후 main() 메서드에서는 반환된 문자열을 split(" ")으로 공백 단위로 나누고, 각 단어의 첫 글자가 a, e, i, o, u 중 하나인지 검사하여 조건에 맞는 단어만 콘솔에 출력합니다.

실행 결과

originated
idea
exists
a
of
on-line
and
at
own
of

추가 팁

위 예제는 소문자 모음만 검사하므로, 대문자로 시작하는 단어도 처리하려면 char ch = Character.toLowerCase(words[i].charAt(0));처럼 첫 글자를 소문자로 변환한 뒤 비교하는 것이 좋습니다. 또한 정규표현식을 선호한다면 str.split("\\s+")로 연속된 공백까지 안전하게 처리하거나, Pattern 클래스의 \\b[aeiouAEIOU]\\w+ 패턴을 사용해 Matcher로 모음으로 시작하는 단어를 한 번에 추출할 수도 있습니다.