Useful String Methods
Find, cut, change case and split text with the String methods indexOf, lastIndexOf, substring, toLowerCase, toUpperCase and split.
Apprentice · Java · Updated
indexOf()
The indexOf method returns the index within the string of the first occurrence of the specified character or substring. If the character or substring is not found, it returns -1.
Example
This example finds the location of the first dash in a phone number. Positions in a string start at 0, so the first dash is at position 3.
public class StringExample
{
public static void main(String[] args)
{
String phoneNumber = "614-555-0123";
int dashIndex = phoneNumber.indexOf('-');
// the dashIndex is 3
System.out.println("The first dash is at index: " + dashIndex);
}
}
lastIndexOf()
The lastIndexOf() method returns the index within the string of the last occurrence of the specified character or substring.
Example
This example finds the position of the last dot (.) in a file name.
public class StringExample
{
public static void main(String[] args)
{
String fileName = "example.file.name.txt";
int lastDotIndex = fileName.lastIndexOf('.');
System.out.println("The last dot is at index: " + lastDotIndex);
}
}
substring()
The substring method returns a new string that is a substring of the specified string. It can be used to extract portions of a string. The substring() method comes in two versions: substring(start, end) returns the characters from start up to, but not including, end; substring(start) returns everything from start to the end of the string.
Example: Get the first name
In this example we want to get only the first name from the fullName variable. We can use the substring method by specifying the start and end positions. To find the end position we can use the indexOf method to find the first space in the name.
public class StringExample
{
public static void main(String[] args)
{
String fullName = "John Doe";
int endPosition = fullName.indexOf(' ');
String firstName = fullName.substring(0, endPosition);
System.out.println("First name: " + firstName);
}
}
substring() with lastIndexOf()
Combining substring with lastIndexOf can be helpful for tasks like finding the text at the end of a string.
Example: Find a file extension
If we want to find the extension of a file, the one-argument version, substring(start), works well: we pass only the starting position and get the rest of the string.
We use lastIndexOf() to find the position of the last dot.
public class StringExample
{
public static void main(String[] args)
{
String fileName = "example.file.name.txt";
int position = fileName.lastIndexOf('.');
String fileExtension = fileName.substring(position + 1);
System.out.println("File extension: " + fileExtension);
}
}
toLowerCase()
The toLowerCase method converts all the characters in the string to lowercase.
Example
Convert user input into all lowercase letters
import java.util.Scanner;
public class StringExample
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string:");
String input = scanner.nextLine();
String lowerCaseInput = input.toLowerCase();
System.out.println("Lowercase version: " + lowerCaseInput);
}
}
toUpperCase()
The toUpperCase method converts all the characters in the string to uppercase.
Example
Convert user input into all uppercase letters.
import java.util.Scanner;
public class StringExample
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string:");
String input = scanner.nextLine();
String upperCaseInput = input.toUpperCase();
System.out.println("Uppercase version: " + upperCaseInput);
}
}
split()
The split method splits the string into an array of substrings based on a specified delimiter.
Example
This example takes a line as input. The line has four pieces of information separated by pipes "|". We will use the split() method to break a single string into an array of four strings.
public class StringExample
{
public static void main(String[] args)
{
String productLine = "123|Laptop|Electronics|999.99";
String[] parts = productLine.split("\\|");
// parts[0] = "123"
// parts[1] = "Laptop"
// parts[2] = "Electronics"
// parts[3] = "999.99"
for (String part : parts)
{
System.out.println(part);
}
}
}
Do it: get the name part of a fan's email
The fan club's welcome page greets each new member by the part of their email address before the @. People type their addresses with random capitals, so the code also changes the name part to small letters.
The function gets one value:
email: the address as the fan typed it, aString("Vanessa.Jones@example.com").
For example:
| Step | The text |
|---|---|
| As typed | "Vanessa.Jones@example.com" |
The @ is at index 13, so the part before it is |
"Vanessa.Jones" |
| In small letters | "vanessa.jones" |
So emailName("Vanessa.Jones@example.com") returns "vanessa.jones".
Your job: write the function String emailName(String email) so it returns the name part.
- Keep only the text before the
@. - Change it to small (lowercase) letters.
- If the text has no
@, return""(an empty string).
Practiced live on the lesson page: write the Java right there and check it.