Home > Articles > Programming > Java

Manipulating Strings

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Searching For and Retrieving Substrings

int result = string1.indexOf(string2);
int result = string1.indexOf(string2, 5);

In the first method shown, the value of result will contain the index of the first occurrence of string2 within string1. If string2 is not contained within string1, -1 will be returned.

In the second method shown, the value of result will contain the index of the first occurrence of string2 within string1 that occurs after the fifth character within string1. The second parameter can be any valid integer greater than 0. If the value is greater than the length of string1, a result of -1 will be returned.

Besides searching a string for a substring, there might be times when you know where a substring is that you are interested in and simply want to get at that substring. So, in either case, you now know where a substring is that you are interested in. Using the String’s substring() method, you can now get that substring. The substring() method is overloaded, meaning that there are multiple ways of calling it. One way of calling it is to pass a start index. This will return a substring that begins at the start index and extends through the end of the string. The other way of using substring() is to call it with two parameters—a start index, and an end index.

String string1 = "My address is 555 Big Tree Lane";
String address = string1.substring(14);
System.out.println(address);

This code will print out

555 Big Tree Lane

The first 5 character is at position 14 in the string; thus it is the beginning of the substring. Note that strings are always zero-based indexed, and the last character of a string is at location (length of string) -1.

  • + Share This
  • 🔖 Save To Your Account