포스트

공백으로 구분하기 2

https://school.programmers.co.kr/learn/courses/30/lessons/181868

문제

  • 문제 풀이

    1
    2
    3
    4
    5
    6
    7
    8
    
      public class Solution {
          public String[] solution(String my_string) {
              // 공백을 기준으로 문자열 나누기
              String[] words = my_string.trim().split("\\s+");
        
              return words;
          }
      }
    
    • split("\\s+")은 연속된 공백을 모두 하나의 구분자로 취급하여 문자열을 나누는 역할을 한다.
      • Java에서 정규 표현식에서 역슬래시 \는 이스케이프 문자로 사용되므로, 실제 공백을 나타내기 위해서는 \\s와 같이 사용한다.
      • +는 하나 이상의 공백을 의미한다. 따라서 \\s+는 하나 이상의 공백을 찾아내는 정규 표현식으로, 이를 기준으로 문자열을 나누게 된다.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    
      import java.util.ArrayList;
      import java.util.List;
        
      public class Solution {
          public String[] solution(String my_string) {
              List<String> words = new ArrayList<>();
              StringBuilder word = new StringBuilder();
                
              // 문자열을 순회하면서 공백을 기준으로 단어를 추출한다.
              for (char c : my_string.toCharArray()) {
                  if (c == ' ') { // 공백을 만나면 지금까지 저장한 단어를 리스트에 추가하고 초기화
                      if (word.length() > 0) {
                          words.add(word.toString());
                          word.setLength(0); // StringBuilder 초기화
                      }
                  } else { // 공백이 아니면 단어를 추가한다.
                      word.append(c);
                  }
              }
                
              // 마지막 단어가 공백으로 끝나지 않는 경우에 추가
              if (word.length() > 0) {
                  words.add(word.toString());
              }
                
              // 리스트를 배열로 변환하여 반환한다.
              return words.toArray(new String[0]);
          }
        
          public static void main(String[] args) {
              Solution sol = new Solution();
              String[] result1 = sol.solution(" i    love  you");
              for (String word : result1) {
                  System.out.print(word + " "); // 출력: i love you
              }
              System.out.println();
                
              String[] result2 = sol.solution("    programmers  ");
              for (String word : result2) {
                  System.out.print(word + " "); // 출력: programmers
              }
              System.out.println();
          }
      }
    
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.