Processing strings
# Topic
String
# Problem
Number of occurrences
Write a program that finds the frequency of occurrences of a substring in a given string. Substrings cannot overlap: for example, the string ababa contains only one substring aba.
Input data format
The first input line contains a string, the second one contains a substring.
Sample Input 1:
ababa
aba
1
2
2
Sample Output 1:
1
1
Sample Input 2:
hello there
the
1
2
2
Sample Output 2:
1
1
Sample Input 3:
hello yellow jello
ll
1
2
2
Sample Output 3:
3
1
# Hint & Explain
Check out the indexOf(String str, int formIndex) method.
# Solution
# My solution
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner(System.in);
String string = scanner.nextLine();
String subString = scanner.nextLine();
int fromIndex = 0;
int occurIndex;
int counter = 0;
do {
if (fromIndex > string.length() - 1) {
break;
}
occurIndex = string.indexOf(subString, fromIndex);
if (occurIndex != -1) {
counter++;
fromIndex = occurIndex + subString.length();
}
} while (occurIndex != -1);
System.out.println(counter);
}
}
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
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
# Other solution 1
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner(System.in);
String sentence = " " + scanner.nextLine() + " ";
String query = scanner.nextLine().trim();
System.out.print(sentence.split(query).length - 1);
}
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# Other solution 2
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String string = scanner.nextLine();
String substring = scanner.nextLine();
System.out.println((string.length() - string.replace(substring, "").length()) / substring.length());
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
编辑 (opens new window)
上次更新: 2023/04/14, 12:58:00