File tree 1 file changed +30
-0
lines changed
1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments