Skip to content

Commit 3fd254d

Browse files
committed
Solution to find the index of first occurence of a word in a String
1 parent 7a06623 commit 3fd254d

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

src/Strings/Strings.java

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ public static void main(String[] args) {
99
// learningCharacterArray("Pradeep");
1010
// reverseString("abcdefg");
1111

12+
int firstIndex = firstOccurenceOfWord("lvnrqpz","rogq");
13+
System.out.println("Index with first occurence of word is " + firstIndex);
14+
1215
Scanner scan = new Scanner(System.in);
1316
String s = scan.nextLine();
1417
System.out.println("String: " + s);
@@ -17,20 +20,28 @@ public static void main(String[] args) {
1720
System.out.println(output);
1821
}
1922

20-
static void firstOccurenceOfWord(String A, String B){
23+
static int firstOccurenceOfWord(String A, String B){
2124

2225
int lengthOfString = A.length();
2326

24-
for (int i = 0; i < lengthOfString; i++) {
25-
26-
for (int j = i+1; j < lengthOfString; j++) {
27-
28-
// if
27+
for (int i = 0; i < lengthOfString+1-B.length(); i++) {
28+
// char matchChar = A.charAt(i);
29+
// String matchString = String.valueOf(matchChar);
30+
String matchString = "";
2931

32+
for (int j = i; j < i+B.length(); j++) {
33+
matchString = matchString + String.valueOf(A.charAt(j));
3034
}
3135

32-
36+
if (matchString.equalsIgnoreCase(B)){
37+
return i;
38+
}
39+
// if (matchString == B){
40+
//
41+
// }
3342
}
43+
44+
return -1;
3445
}
3546

3647
static String reverseWordsInASentence(String S){

0 commit comments

Comments
 (0)