반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- string
- 문자열
- Button
- js
- Eclipse
- 자바
- list
- 이탈리아
- 테이블
- table
- 인텔리제이
- input
- ArrayList
- windows
- 정규식
- Java
- 이클립스
- vscode
- html
- Array
- IntelliJ
- Maven
- javascript
- json
- 배열
- date
- CSS
- CMD
- 자바스크립트
- Visual Studio Code
Archives
- Today
- Total
어제 오늘 내일
[Java] 문자열에서 특정 문자 개수 구하는 3가지 방법 본문
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가지 방법을 알아보았습니다.
반응형
'IT > Java' 카테고리의 다른 글
[Java] String 문자열을 char 배열로 변환하기 (0) | 2021.04.29 |
---|---|
[Java] char 배열을 String 문자열로 변환하기 (0) | 2021.04.29 |
[Java] 문자열에 특정 문자 포함 여부 확인하기 - contains, indexOf, matches (3) | 2021.04.28 |
[Java] String <-> boolean 변환하기 (0) | 2021.04.28 |
[Java] 구분자로 문자열 자르기 (split) (0) | 2021.04.28 |