본문 바로가기
수업(국비지원)/Java

[Java] chap11: 기본 API(패키지 클래스) - 기본 API Exam2.(count 메서드 구현)

by byeolsub 2023. 4. 16.
count 메서드 구현하기
  int count(문자열소스,찾는 문자열) : 문자열 소스에서 찾는 문자열의 갯수를 리턴

 

📌

package chap11;

public class Exam2 {
	public static void main(String[] args) {
		System.out.println(count("12345AB12AB345AB","12"));//2
		System.out.println(count("12345AB12AB345AB","AB"));//3
		System.out.println(count("12345","6"));            //0
	}
	private static int count(String s1, String s2) {
		//"12345AB12AB345AB","AB"
		int cnt=0;
		int index = 0;
		while(true) {
			index = s1.indexOf(s2,index);//-1
			if(index < 0) break;
			cnt++; //2
			index++;//8
		}
		return cnt;
	}
}