Algorithm/SWEA

[SWEA] S/W 문제해결 기본(3) - String

goakgoak 2020. 4. 16. 18:31

[1213] String

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV14P0c6AAUCFAYi

  • 주어지는 영어 문장에서 특정한 문자열의 개수를 반환하는 프로그램을 작성하여라.
  • Starteatingwellwiththeseeighttipsforhealthyeating,whichcoverthebasicsofahealthydietandgoodnutrition.
  • 위 문장에서 ti를 검색하면, 답은 4이다.

 

 

Solution

  • String 함수 split(String regex, int limit)을 사용해서 문제해결
  • regex는 구분자, limit가 음수이면 문장끝에 일치하는 구분자까지 포함하여 마지막 요소가 ""인 배열을 반환한다.
  • 예를들어,
  • String str = "hello&java&";
  • String[] arr = str.split("&", -1);
  • arr = {"hello", "java", ""}; 을 반환한다.

 

 

소스코드

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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
 
public class Solution {
    static int T, n, m, answer;
    static StringTokenizer st;
 
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 
        while (true) {
            T = stoi(br.readLine());
            String split = br.readLine();
            String[] arr = br.readLine().split(split-1);
            
            answer = arr.length - 1;
            System.out.println("#" + T + " " + answer);
 
            if (T == 10)
                break;
        }
 
    }
 
    static void init() {
        
    }
 
    static int stoi(String s) {
        return Integer.parseInt(s);
    }
}
cs