Java for Humans {String Manipulation}

Lincoln W Daniel
Jan 17, 2016 · 9 min read
View Table of Contents | Download Supporting Code | Subscribe to ModernNerd Youtube Channel for Coding Videos | By Lincoln W Daniel

Java Strings are powerful. While a String seems simple as a mere representation of character strings, they are one of the best ways to store information, data in Java. Because character strings are so vital to programming, the creators of Java decided to dedicate an entire class to them and give that class useful methods to make data manipulation easier. In this chapter, we will learn how to use some of the instance methods of the String class to compare strings, search a string for individual characters or substrings, extract substrings, and more. It is not necessary that you read this whole chapter, but it is important that you know these functions are available to you.

Why String Manipulation is Important & Useful

Often times in your programs, you will be presented with data which you can store as a String. When you have the data stored as a String instance, you can use the instance methods of the String class to manipulate the data. This functionality allows you to do more things with the data you have.

Comparing Strings

A operation you will run many times in your programs is a operation to compare two String instances to one another. If you have a Facebook account, you will be asked for your username and password when you try to log in. Behind the scenes, Facebook will compare the username and password you provide to the username and password they have stored in their database for your account. If the comparisons are successful, you can log in, but if they fail, you will have to try again.

The String class has convenient comparison instance methods for us to compare two instances. We can use equals() to compare two strings case sensitively or equalsIgnoreCase() to compare without considering the case of the strings. Both of these methods return a boolean — true if the comparisons succeed and false otherwise. Let’s emulate a social network login process in Java:

String usernameInDatabase = "modernNerd";
String passwordInDatabase = "mN123Java";

String providedUsername = "modernnerd";
String providedPassword = "mN123Java";
//successful username comparison
//check the provided password

//this will fail

//this will pass
System.out.println("Success! You are logged in.");
} else {
System.out.println("Wrong password. Try again.");
} else {
//user provided wrong username
System.out.println("Wrong username. Try again.");

If the username provided by the user, providedUsername, matches the username in the database, usernameInDatabase, regardless of case, we want to check if the password provided by the user, providedPassword, matches the password in the database, passwordInDatabase, with regards to the case. If all of the string comparisons pass, we can let the user log in.

Counting Characters in a String

Some social networking applications, such as Twitter, allow users to post messages with a maximum length. They capture the message the user enters as a String, count the length of the message, and use its length to decide whether or not to let the user post the message. We can do that with the length() instance method:

String message = "Hello, world! My name is Lincoln";
int messageLength = message.length();
if(messageLength <= 140) {
//send the message

Getting Index of a Character in a String

If you want to know the index of the first occurrence of a character in a string, you can use the indexOf() instance method on a String instance. Remembering that indices in Java and other programming languages start at zero, we can try to get the index of the the letter “D” in a string containing the entire alphabet:

int indexOfLetterD = alphabet.indexOf("D");
//indexOfLetterD equals 3

Although “D” is the fourth letter in the English alphabet, it is at the third index in the String instance, and that’s exactly what is returned by indexOf().

Getting Index of a Substring in a String

Other times, you may not only want to know the index of a single character. Instead, you may want to know the index of the first occurrence of an entire substring of a String instance. Say you want to get the start of the ending characters of the alphabet. The indexOf() instance method will return where the substring begins as the index of the first character in the substring:

int beginningOfTheEnd = alphabet.indexOf("XYZ");
//beginningOfTheEnd equals "22"

The letter “X” is the 24th letter in the alphabet, but it’s at the 23rd index in the String instance. The substring “XYZ” of the alphabet String instance starts with “X”, so that substring begins at the 23rd index; that is what indexOf() returns here.

Extracting a Substring From a String

There may be some times when we only want a part of a string. In such cases, we want to extract a substring from a string. One of those cases may be when we have a long string but we only want the second half of it. We can use the substring() instance method on our String instance to get the first half of it by passing in one argument which will tell the method at which index of the string to start extracting our substring. Another way to think of the method’s argument is that it tells the substring() method how many characters, from the left, it should skip. Given that, we can get the second half of our alphabet string by providing half its length as the argument of the substring() method:

String secondHalfOfAlphabet = alphabet.substring(13);

While that works, there is a more dynamic approach to the above that allows our code to adapt to a change in the length of the alphabet in the case its length changes from 26 to something else, say 20. In such a case, 13 would no longer be half the length of the alphabet, so we should prepare for that by doing the following:

String secondHalfOfAlphabet = alphabet.substring(alphabet.length() / 2);

Now imagine your friend asks you for your street address and city, but you only have the entire string of your house address which contains the street address, city, state, zip code, and country. You may not want to send her your entire address because she only cares about your street address and city. In this case, you would need to manipulate the String containing your full address to get only the part containing your street address and city and store it in a new variable to send to her.

Knowing that the street address and the city come before the comma in your full address, you can use the substring() method along with the indexOf() method to get that part of the string containing your street address:

String fullAddress = "123 JavaStreet JavaCity, JavaState 19081 United States";String streetAddressAndCity = fullAddress.substring(0, fullAddress.indexOf(","));

The first argument of the substring() method tells the method where to begin extracting the substring while the second tells it where to end the substring. Together, the arguments declare the range of the substring we want the method to return. The range is inclusive of the first argument and exclusive of the second; in our street address and city example, the substring will begin at index zero (0) of fullAddress and end right before the index of the comma. Here’s the result of our operation:

//prints "123 JavaStreet JavaCity"

Converting Case of Strings

There will be times when you have a word in a case other than what you need it in, so it’s nice to know that you can convert it to either all uppercase or all lowercase characters when stored in a String instance by using its toLowerCase() and toUpperCase() instance methods. A good use of such functionality would be to ensure consistency of the data you store in a database. Making sure all of the data you get from a user is lowercase before you store it in your database will make your database easier to search through later. This is also good for the users who do not want to worry about the case of the information they provide to your program. You can let the user enter information in any case they want and convert it to the necessary case behind the scenes for your program:

String name = "Lincoln Daniel";
String lowercaseName = name.toLowerCase();
String uppercaseName = name.toUpperCase();
System.out.println("Lowercase name: " + lowercaseName);
//prints "Lowercase name: lincoln daniel"
System.out.println("Uppercase name: " + uppercaseName);
//prints "Uppercase name: LINCOLN DANIEL"

Bonus: Figure out how to capitalize the string; only make the first letter in a String uppercase. You may need to use the substring() instance method.

String Replacement

Another useful tool provided to us in the String class is a method to replace a substring in a string with another string. If you want to change your last name, you can call the the replace() instance method on the string storing your full name. The replace() method takes two arguments — the substring you want to replace and the string to replace it with — and finds all occurrences of the first argument and replace them with the replacement. Finally, it will return the new String instance to you with the replacement. Let’s change my first name:

String newName = name.replace("Lincoln", "Modern");
//prints "Modern Daniel"

My name is now “Modern Daniel”. Let’s finish by changing my last name to “Nerd”:

String newName2 = newName.replace("Daniel", "Nerd");
//prints "Modern Nerd"

Now my name is “Modern Nerd” and that new string is saved in the newName2 String variable. However, if you want to access my original name, you can still do so because we did not change the value of our name variable. The name variable still holds my original name because the replace() method copies the string it is called on and returns the copy after modifying it. The original string is never modified because String instances are immutable. Immutable data cannot be mutated, or changed. Note that the name variable is mutable because it’s a variable, but the String instance it holds is the data that is immutable. Therefore, if we wanted to overwrite our original name in the name variable, we could do the follow:

//prints "Lincoln Daniel" because it hasn't been modified
name = newName2;
//prints "Modern Nerd"

Splitting a String into Tokens

If you’ve ever written an essay for homework, you have likely been instructed to make sure your essay consists of exactly a certain amount of words. As you write it, you constantly check the amount of words you’ve written to check how far you are from completing the essay. Many word document editors have a tool to help you count the amount of words you’ve written so you don’t have to sit there and count your words on your own. Until now, how the editor does the word counting may have been a mystery to you. Let’s see how easy it is to split a String instance and count the amount of words in it by making use of the split() instance method.

If you want to know how many words are in an string holding an essay, knowing that words are usually separated by a single empty space, you can provide an empty string with a length of one — a space — to the split() method in order to get all the tokens in the string as an array and count the number of tokens, elements in the array. Let’s try it out:

String essay = "The ModernNerd coded everyday to build something great.";String[] allWordsInEssay = essay.split(" ");
int numWordsInEssay = allWordsInEssay.length;
System.out.println("Word Count: " + numWordsInEssay);
//prints "Word Count: 8"

The split() method takes a delimiter as its single argument. The delimiter tells the method how to split the string up into tokens. Tokens are simply the parts, substrings, of the string as delimited by the provided delimiter. You can provide any string as your delimiter, and the method will return an array holding all of the tokens it could create from your string and your delimiter. If it doesn’t find your delimiter in your string, it will only return one token, the original string, in the resultant array.

We will learn more about Java arrays soon, but know that they simply store a collection of data of the same datatype and every array has a handy length field that holds an integer representing the amount of elements in the array.

There are more methods provided to us in the String class for the purposes of manipulating strings, but the ones we have learned in this chapter are all you need to get started.

ModernNerd Code

Learn to Code Life. Subscribe to Video Tutorials on Youtube

Lincoln W Daniel

Written by

My passion is in developing software to enable people to accomplish their goals more efficiently. Author Creator of

ModernNerd Code

Learn to Code Life. Subscribe to Video Tutorials on Youtube

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade