본문 바로가기

개발새발 개발자/Java

[Java] String 다루기 - parseInt, StringTokenizer, split

지난 번에 콘솔 입력으로 받은 String을 알맞게 다루는 법을 알아볼게요!

 

1. parseInt: 숫자로 변환하기

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

저번에 살펴본 콘솔 입력편에서 BufferedReader는 String을 반환한다고 했습니다. 만약에 숫자처럼 사용하고 싶다면? 번거롭지만 int로 변환하는 과정이 필요합니다.

 

int n = Integer.parseInt(br.readLine());

그래서 필요한 게 바로 parseInt입니다! BufferedReader인 br로 받는 text를 전부 int형으로 변환해줍니다.

 

 

2. StringTokenizer: 쪼개기

StringTokenizer st = new StringTokenizer(br.readLine());

int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());

StringTokenizer는 String을 쪼갤 때 사용합니다. 우리가 받은 text는 stream이기 때문에 주르르르르륵 이어져있거든요. 만약 1 2라고 입력했으면 1과 2를 따로 사용하기 위해 StringTokenizer로 쪼갭니다.

 

 

public StringTokenizer(String str)

The tokenizer uses the default delimiter set, which is " \t\n\r\f": the space character, the tab character, the newline character, the carriage-return character, and the form-feed character.

공식 문서를 보면 스페이스, 탭, 엔터 같이 공백을 기준으로 잘라낸다고 합니다.

 

public StringTokenizer(String str, String delim)

The characters in the delim argument are the delimiters for separating tokens. Delimiter characters themselves will not be treated as tokens. 

만약 쉼표나 다른 기호를 기준으로 잘라내고 싶다면 'delim' 자리에 기호를 지정해줄 수도 있어요.

 

3. split(): 쪼개기

또 다른 쪼개기(?)를 소개할게요.

 

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String instead.

공식 문서를 쭉 읽어보니 이런 내용이 있더라구요. 앞에서 배운 StringTokenizer가 legacy래요!!(두둥)

 

만약 StringTokenizer처럼 쪼개는 함수를 사용하고 싶다면 split()을 사용하라고 하네요.

 

String s = "cha eun woo";
String result = s.split("\\s");

만약 s라는 String에 "cha eun woo" 라는 텍스트가 있다고 해볼게요. split()은 ()안에 들어있는 기호를 기준으로 글자를 잘라내요. 해당 기호는 결과에 포함되지 않구요!

 

split의 구분자는 정규 표현식을 받을 수 있어요. 여기서 \\s는 공백을 뜻하는 정규 표현식입니다. 그럼 공백을 기준으로 텍스트를 자르되, 구분자인 공백은 포함되지 않게 나오겠죠?

 

cha
eun
woo

그래서 결과는 이렇게 출력됩니다 :)

 

쪼개는 개수를 제한하고 싶다면 어떻게 할까요? 예를 들어 cha까지만 자르고 eun woo를 한 줄에 쓰고 싶다면?

String s = "cha eun woo";
String[] result = s.split("\\s", 2);

뒤에 붙은 n의 n-1만큼 즉, 여기서는 1번째까지만 적용되고 끝나게 됩니다.

 

cha
eun woo

짠! 이렇게 eun woo가 같은 줄에 붙어서 나왔습니다!