How to Break a String Into Substrings in Java

The Java "substring" function lets you retrieve a part of a string and assign the new value to another variable. This feature is useful when you want to extract a part of a string and use the value for other calculations in your code. To use the "substring" function, you specify the start position of the string you want to cut out and specify the ending position where you want the function to stop extraction of the string.

Instructions

    • 1

      Right-click the Java file in which you want to perform the substring function. Click "Open With" and click your Java editor.

    • 2

      Create a string variable, if you do not already have a string you want to use in the substring function. The following code creates a string in Java:

      string mystring = "My String";

    • 3

      Create a string variable to contain the substring. The following code creates another string for your substring:

      string mysubstring = "";

    • 4

      Perform the substring function on the main string created in step two. The following code retrieves "My" from the original string:

      mysubstring = mystring.substring(0, 1);

      The first character in the string starts at the "0" index. In this example, the string characters from position 0 to position 1 are copied, which is the "My" text from the string.

Related Searches:

References

Comments

Related Ads

Featured