1. 반복문 이용하기
public class CharCountTest {
public static void main(String[] args) {
String str = "soultree";
System.out.println(countChar(str, 's')); //1
System.out.println(countChar(str, 'o')); //1
System.out.println(countChar(str, 'u')); //1
System.out.println(countChar(str, 'l')); //1
System.out.println(countChar(str, 't')); //1
System.out.println(countChar(str, 'r')); //1
System.out.println(countChar(str, 'e')); //2
}
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;
}
}
2. replace() 이용하기
public class CharCountTest {
public static void main(String[] args) {
String str = "soultree";
System.out.println(countChar(str, 's')); //1
System.out.println(countChar(str, 'o')); //1
System.out.println(countChar(str, 'u')); //1
System.out.println(countChar(str, 'l')); //1
System.out.println(countChar(str, 't')); //1
System.out.println(countChar(str, 'r')); //1
System.out.println(countChar(str, 'e')); //2
}
public static int countChar(String str, char ch) {
return str.length() - str.replace(String.valueOf(ch), "").length();
}
}