Skip to content

Commit 5a17f94

Browse files
Create 33.1 String Find Nth Occurence.java
1 parent 66ca93d commit 5a17f94

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

33.1 String Find Nth Occurence.java

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/*
2+
Chacha Chaudhary has asked Sheena to find out the Nth occurence of any Word in the Paragraph. Sheena finds it a tedious task to find Nth occurence so she wants you to write a small java program which can solve her problem and she will give you a gift for helping her. Let us write a code.
3+
4+
Input Format
5+
6+
First line reads the paragraph contents
7+
8+
Second line reads the word to be found and N separated by Space
9+
10+
Constraints
11+
12+
N>0
13+
14+
Output Format
15+
16+
Prints the starting index of the Nth occurence of the word in the paragraph
17+
18+
Prints Not Present if not occuring even a single time and prints the last occurence if occuring less than N times.
19+
20+
Sample Input 0
21+
22+
Aana bought banana.
23+
ana 1
24+
Sample Output 0
25+
26+
1
27+
Sample Input 1
28+
29+
Aana bought banana
30+
baa 3
31+
Sample Output 1
32+
33+
Not Present
34+
Sample Input 2
35+
36+
Aana bought banana.
37+
ba 3
38+
Sample Output 2
39+
40+
12
41+
Explanation 2
42+
43+
ba is occuring only 1 time i.e. at index 12. 3rd occurence is not available so output is 12 which is the last occurence.
44+
*/
45+
46+
47+
import java.io.*;
48+
import java.util.*;
49+
50+
public class Solution {
51+
52+
public static void main(String[] args) {
53+
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
54+
Scanner sc = new Scanner(System.in);
55+
String para = sc.nextLine();
56+
String tofind = sc.next();
57+
int occurence = sc.nextInt();
58+
int index = para.indexOf(tofind);
59+
int final_= index;
60+
int count = 1;
61+
while(index!=-1&&count++<occurence)
62+
{
63+
index = para.indexOf(tofind,(index+1));
64+
if(index!=-1)
65+
final_ = index;
66+
}
67+
if(final_==-1)
68+
System.out.println("Not Present");
69+
else
70+
System.out.println(final_);
71+
72+
73+
}
74+
}

0 commit comments

Comments
 (0)