How to Find a Substring in Java

In Java, a string is an array of characters (letters, numbers or symbols). A substring of a string is simply a collection of characters contained within the string. For example, the string "My name is Hal" has substrings "My," "Hal," "ame," etc. At some point, when working with strings in Java, you will need to check whether a certain substring is contained in a string. The best way to do this is to use the indexOf() method on the string in question.

Instructions

    • 1

      In the Main method of your Java program, create an arbitrary string by typing the following code:
      String phrase = "My name is hal";

    • 2

      Declare an integer to hold the result of your substring search by typing the following code:
      int i;

    • 3

      Run the indexOf() method on your String, and give its result to the variable declared in the previous step by typing:
      i = phrase.indexOf("name");

    • 4

      Print out the result of "i" by typing the line:
      System.out.println("result of search: "+i);

      If the substring you searched for in Step 3 (the substring "name" in our example) was not found, the result will be -1. If it was found, the result will be equal to the starting index of the substring (remember that in Java, a string is an array of characters). In our example this number is 3, because the substring begins after the 3rd character in the string.

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured