String Search Algorithm in Java

The String Search Algorithm is a fundamental technique in Java programming used to search for a specific substring within a larger string. This algorithm is widely employed in various text processing applications, including text editors, search engines, and data analysis tools.

How the String Search Algorithm Works

The String Search Algorithm works by comparing each character of the substring being searched with the characters of the main string. It iterates through the main string and checks for a potential match by comparing characters one by one. If a match is found, it indicates the starting position of the substring within the main string.

Advantages and Disadvantages of the String Search Algorithm

Advantages:

  • Simple Implementation: The algorithm is easy to understand and implement, making it suitable for basic string searching tasks.
  • Applicable to Various Scenarios: This algorithm can be used in a wide range of applications that involve searching for specific patterns within text data.

Disadvantages:

  • Inefficient for Large Texts: In worst-case scenarios, the algorithm's time complexity can become high, making it inefficient for large texts.
  • Limited Pattern Matching: The basic version of the algorithm might not handle complex pattern matching requirements.

Example and Explanation

Let's consider an example of using the String Search Algorithm to find a specific word in a sentence in Java.

public class StringSearchExample {
    public static int searchString(String mainString, String substring) {
        int mainLength = mainString.length();
        int subLength = substring.length();

        for (int i = 0; i <= mainLength - subLength; i++) {
            int j;

            for (j = 0; j < subLength; j++) {
                if (mainString.charAt(i + j) != substring.charAt(j)) {
                    break;
                }
            }

            if (j == subLength) {
                return i; // Substring found at position i
            }
        }

        return -1; // Substring not found
    }

    public static void main(String[] args) {
        String text = "The quick brown fox jumps over the lazy dog";
        String search = "fox";

        int position = searchString(text, search);

        if (position != -1) {
            System.out.println("Substring found at position: " + position);
        } else {
            System.out.println("Substring not found");
        }
    }
}

In this example, the algorithm searches for the substring "fox" within the given text. It iterates through each character of the text, comparing it with the characters of the substring. When a match is found, the algorithm returns the starting position of the substring in the text.

This illustrates how the String Search Algorithm can locate substrings within larger text data, making it an essential technique for text manipulation and analysis in Java programming.