Skip to content

Commit 6ae18bb

Browse files
committed
[Manan] ADD:Counting the occurence of a substring in a string
1 parent 183acf4 commit 6ae18bb

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

SubstringOccurences.java

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import java.util.Scanner;
2+
3+
class SubstringOccurences {
4+
// Main method
5+
public static void main(String[] args) {
6+
Scanner input = new Scanner(System.in);
7+
8+
System.out.print("Enter a string: ");
9+
String str = input.nextLine();
10+
11+
System.out.print("Enter a substring: ");
12+
String subStr = input.nextLine();
13+
14+
// Method to calculate number of times a substring occurs in the String
15+
int result = substringOccurences(str, subStr);
16+
17+
System.out.println("Number of times the substring " +subStr+ " occurs in the string: " + result);
18+
}
19+
20+
// Method to calculate number of times a substring occurs in the String
21+
public static int substringOccurences(String str, String subStr) {
22+
int count = 0;
23+
for (int i = 0; i < str.length(); i++) {
24+
if (str.substring(i).startsWith(subStr)) {
25+
count++;
26+
}
27+
}
28+
return count;
29+
}
30+
}

0 commit comments

Comments
 (0)