Home > Software engineering >  Substring search in String (Java)
Substring search in String (Java)

Time:01-27

I want to search the entered letters in the entered text (Ctrl f algorithm). I want to keep the indexes of the letters it finds in an array and then print that array to the console. I wrote this code but it is not working properly. Prints the length of the entered text. I'm a beginner and I'm open to critiques to optimize my code :) Could you please help? ///

For example;

My input text : "muammer akca akca"

My input search : "ak"

Output : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 17 out of bounds for length 17 at Assignment5_2.main(Assignment5_2.java:17)

Expected output :

8

13


8 and 13 are "ak" indexes

Another example:

My input text : "Sotirios Delimanolis"

My input search : "ri"

Output : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 17 out of bounds for length 17 at Assignment5_2.main(Assignment5_2.java:17)

Expected output :

4

4 is "ri" index number

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Assignment5_2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String text = scanner.nextLine();
        String search = scanner.nextLine();
        char[] textArray = text.toCharArray();
        char[] searchArray = search.toCharArray();
        int i,j;
        List<Integer> foundedArray = new ArrayList<Integer>();
        boolean foundControl = true;
        for (i=0 ; i< textArray.length ; i  ){
            foundControl = true;
        } for (j=0 ; j<searchArray.length ; j  ){
            if (textArray[i j] != searchArray[j]){
                foundControl = false;
                break;
            }
        }
        if (foundControl){
            foundedArray.add(i);
            System.out.println(i);
        }
        for (i=0;i<foundedArray.size() ; i  ){
            System.out.println(foundedArray.get(i));
        }
    }
}

CodePudding user response:

This code should do it.

String input = "akmuammer akca akca";
String test = "ak";
List<Integer> indexes = new ArrayList<>();
int index = -1;
do {
    index = input.indexOf(test, index   1);
    if (index > -1) {
        indexes.add(index);
    }
} while (index > -1);
System.out.println(indexes);

I had to update the code in order for it to count an occurrence of the test pattern at index 0. The previous version would've missed this case.

For the current input, it will return [0, 10, 15]. For the OP's input, it will return [8, 13]. If no match is found, it will simply return an empty list.

  •  Tags:  
  • Related