Write a method header on line two with the following specs:
Returns: an integer Name: countString Parameters: a String called str a String called toFind Purpose: Count the number of occurrences of toFind within str. See below examples. |
Examples:
- countString("crazy crayfish crushing craniums", "cra") ==> 3
- countString("sometimes solutions dont come on time", "me") ==> 4
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
class Main {
public static int countString(String str,String toFind)
{
int cnt=0;
for(int i=0;i<str.length()-toFind.length()+1;i++) {
if(str.substring(i,i+toFind.length()).equals(toFind)) {
cnt++;
}
}
return cnt;
}
//test case below (dont change):
public static void main(String[] args){
System.out.println(countString("crazy crayfish crushing craniums", "cra")); //3
System.out.println(countString("sometimes solutions dont come on time", "me")); //4
}
}
|
반응형
'Java_beginner(Repl.it) > Auto-Graded-Course(AP CS A)' 카테고리의 다른 글
053 - Accumulator Method String Practice 1 (0) | 2019.12.26 |
---|---|
052 - Accumulator Method Challenge 2 (optional) (0) | 2019.12.26 |
050 - Accumulator Method Practice 6 (0) | 2019.12.26 |
049 - Accumulator Method Practice 5 (0) | 2019.12.26 |
048 - Accumulator Method Practice 4 (0) | 2019.12.26 |