How to Discover if a Certain Substring Exists in a String in Java

How to Discover if a Certain Substring Exists in a String in Java thumbnail
Use Java to search for strings.

Java is a powerful, widely used object-oriented programming language. Compiled Java code runs on multiple operating systems and devices from Windows and Mac PCs to smartphones and ATMs. Languages such as Java use strings, which are letters or chains of characters, such as a sentence. Java developers often have to search a long string for the occurrence of a substring, which for instance could be a particular word in a sentence. In Java, strings are actually objects and have many methods that can operate on them. You can search a string for a substring using the string.indexOf() method.

Things You'll Need

  • Installed Java compiler
Show More

Instructions

    • 1

      Define a string in which to search as follows:

      String input = "This is a test, only a test";

    • 2

      Define a string to search for:

      String test = "test";

    • 3

      Test for the substring "test" in the main string. Use the indexOf() method to determine the index at which the word "test" appears in the string defined as input:

      int index = input.indexOf(test);

    • 4

      The indexOf() method returns a value of -1 if the substring is not found and the index if it is found. You can test for existence and print out the results with:

      if (index != -1)
      System.out.println("Found the string " + " \"" + test + " \"" + " at location: " + index) ;
      else
      System.out.println(" \"" + test + " \"" + " not found!") ;

    • 5

      Patching the pieces together into a complete piece of code looks like the following:

      //An exmaple of string searching
      class Example {
      public static void main(String[] args){
      // create a string that we can search through
      String input = "This is a test, only a test";

      // Now define what string to test for in the input string
      String test = "test";

      // indexOf() is a method that operates on the string, returning
      // the position in the string that the string or character in question
      // is found, or -1 if it is not found
      int index = input.indexOf(test);

      // test and print out the results
      if (index != -1)
      System.out.println("Found the string " + " \"" + test + " \"" + " at location: " + index) ;
      else
      System.out.println(" \"" + test + " \"" + " not found!") ;

      } \\ closes main block
      } \\ closes class

Related Searches:

References

  • Photo Credit Ablestock.com/AbleStock.com/Getty Images

Comments

Related Ads

Featured