어제 오늘 내일

[Java] 문자열에서 특정 문자 개수 구하는 3가지 방법 본문

IT/Java

[Java] 문자열에서 특정 문자 개수 구하는 3가지 방법

hi.anna 2021. 4. 29. 06:36

 

Java 문자열에 포함된

특정 문자의 개수를 구하는 방법 3가지를 알아보도록 하겠습니다.

 

 

1. 반복문 이용하기

  코드  

public class CharCount {
public static void main(String[] args) {
String str = "apple";
System.out.println(countChar(str, 'a')); // 1
System.out.println(countChar(str, 'p')); // 2
System.out.println(countChar(str, 'l')); // 1
System.out.println(countChar(str, 'e')); // 1
System.out.println(countChar(str, 'c')); // 0
}
public static int countChar(String str, char ch) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ch) {
count++;
}
}
return count;
}
}

  결과  

1
2
1
1
0

가장 간단하게 반복문을 이용하여, 특정 문자의 개수를 세는 방법입니다.

 

 

 

2. Stream 이용하기 (Java 8 이후 버전)

  코드  

public class CharCount {
public static void main(String[] args) {
String str = "apple";
System.out.println(countChar(str, 'a')); // 1
System.out.println(countChar(str, 'p')); // 2
System.out.println(countChar(str, 'l')); // 1
System.out.println(countChar(str, 'e')); // 1
System.out.println(countChar(str, 'c')); // 0
}
public static long countChar(String str, char ch) {
return str.chars()
.filter(c -> c == ch)
.count();
}
}

  결과  

1
2
1
1
0

Java 8 이후에서부터 사용할 수 있는 Stream을 이용한 방법입니다.

 

 

 

3. replace() 이용하기

  코드  

public class CharCount {
public static void main(String[] args) {
String str = "apple";
System.out.println(countChar(str, 'a')); // 1
System.out.println(countChar(str, 'p')); // 2
System.out.println(countChar(str, 'l')); // 1
System.out.println(countChar(str, 'e')); // 1
System.out.println(countChar(str, 'c')); // 0
}
public static int countChar(String str, char ch) {
return str.length() - str.replace(String.valueOf(ch), "").length();
}
}

  결과  

1
2
1
1
0

java.lang.String 클래스의 replace() 메소드를 이용한 방법입니다.

 

str.replace(String.valueOf(ch), "");

replace() 메소드를 이용해서

개수를 세고자 하는 문자를 찾아서, 이 문자를 공백("")으로 변환하였습니다.

그러면, 개수를 세고자 하는 문자의 갯수만큼, 문자열의 길이가 줄어들게 됩니다.

 

str.replace(String.valueOf(ch), "").length();

찾는 문자를 모두 공백으로 변경하고, 그 문자열의 길이를 찾았습니다.

 

str.length() - str.replace(String.valueOf(ch), "").length();

그러면,

찾는 문자의 개수 = 원본 문자열의 길이 - 찾는 문자를 모두 공백으로 변경한 문자열의 길이

이렇게 찾는 문자의 개수를 계산할 수 있게 됩니다.

 


 

문자열에서 특정 문자의 갯수를 찾는 3가지 방법을 알아보았습니다.

 

 

 

반응형
Comments