[Java] 문자열내 특정 문자 개수 확인

프로그래밍/JAVA 2019. 5. 29. 23:06 posted by 야매코더

자바 문자열내 특정한 문자의 개수를 확인할때 사용하는 샘플 코드 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class StringParse {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String s = "!@dddddd!@gggg!@bbbbbttt!@";
        int cnt = getCount(s);
        System.out.println(cnt);
    }
 
    public static int getCount(String s) {
        int count = 0;
         
        Pattern p = Pattern.compile("!@");
        Matcher m = p.matcher(s);
         
        for (int i = 0; m.find(i); i = m.end()) {
            count++;
        }
        return count;
    }
}