In this How to Program with Java post we will talk about more advanced aspects of String manipulation. With every programming project I have worked on in my career, I’ve needed to use different strategies related to manipulating Strings. So this topic is critical to learning Java and being a solid programmer (in any language really).

What is String Manipulation?

At this point you should be familiar with what a String datatype is in Java. Strings are a popular datatype and there are a wealth of tools that can be used to modify their contents. Let’s say you have the following code:

List < String > websites = new ArrayList < String > ( ) ; websites. add ( "https://howtoprogramwithjava.com/reviews/" ) ; websites. add ( "https://howtoprogramwithjava.com/programming-101-the-5-basic-concepts-of-any-programming-language/" ) ; websites. add ( "https://howtoprogramwithjava.com/consulting/web-application-development/" ) ; websites. add ( "http://google.com/" ) ; List<String> websites = new ArrayList<String>(); websites.add("https://howtoprogramwithjava.com/reviews/"); websites.add("https://howtoprogramwithjava.com/programming-101-the-5-basic-concepts-of-any-programming-language/"); websites.add("https://howtoprogramwithjava.com/consulting/web-application-development/"); websites.add("http://google.com/");

Now, let’s say we want to isolate two parts of each of these websites, the root URL and the pages within. So, for example, we want to break each one into two parts like so:

"howtoprogramwithjava.com", "reviews" "howtoprogramwithjava.com", "programming-101-the-5-basic-concepts-of-any-programming-language" "howtoprogramwithjava.com" ,"consulting", "web-application-development" "google.com"

How would we go about accomplishing this? Well, we would need to use a method called split() . What this method does is allow you to separate one String into an Array of String s based on a character of your choosing. In our examples, you’ll notice that the forward slash (/) is used to separate the base URL with the individual pages. So this forward slash (/) character would be perfect for splitting up our String s. So, what would that look like?

for ( String website : websites ) // iterate through each website in the ArrayList { System . out . println ( "website: " + website ) ; String [ ] stringArray = website. split ( "//" ) ; System . out . println ( "Splitting String by // = " + Arrays . toString ( stringArray ) ) ; System . out . println ( "Splitting String further by / ->" + Arrays . toString ( stringArray [ 1 ] . split ( "/" ) ) ) ; System . out . println ( "" ) ; // blank space } for (String website: websites) // iterate through each website in the ArrayList { System.out.println("website: " + website); String[] stringArray = website.split("//"); System.out.println("Splitting String by // = " + Arrays.toString(stringArray)); System.out.println("Splitting String further by / ->" + Arrays.toString(stringArray[1].split("/"))); System.out.println(""); // blank space }

This code will split the String s twice. Once with the double forward slash (//) to isolate the “http://” section from the rest. Then it will split the resulting String array once again by a single forward slash (/), which will separate all the individual sections of the URL. The output will look like this:

The split() method is very powerful and it allows you to use something called Regex to identify the parts of the String to split up. Now, Regex is a fairly advanced topic, but if you feel like learning more about it right now you can check out this Introduction to Regex.

Searching Strings

Perhaps you’ll find yourself in a scenario where you’ll need to find out if a particular String exists INSIDE of another String . This will require you to search through your String . Let’s say we have the sentence “The quick brown Fox jumps over the lazy Dog”, and we want to see if that sentence has the word “Fox” in it. Well, then you would use the contains() method. Example:

String sentence = "The quick brown Fox jumps over the lazy Dog." ; boolean sentenceContainsFox = sentence. contains ( "Fox" ) ; System . out . println ( "Does the sentence contain 'Fox': " + sentenceContainsFox ) ; String sentence = "The quick brown Fox jumps over the lazy Dog."; boolean sentenceContainsFox = sentence.contains("Fox"); System.out.println("Does the sentence contain 'Fox': " + sentenceContainsFox);

The output of this will be:

Does the sentence contain ‘Fox’: true

One interesting thing to note though, is if we made one minor change to the code. What if we change the contains method to look for the String “fox” (with a lowercase ‘F’). What do you think Java will output?

String sentence = "The quick brown Fox jumps over the lazy Dog." ; boolean sentenceContainsFox = sentence. contains ( "fox" ) ; System . out . println ( "Does the sentence contain 'fox': " + sentenceContainsFox ) ; String sentence = "The quick brown Fox jumps over the lazy Dog."; boolean sentenceContainsFox = sentence.contains("fox"); System.out.println("Does the sentence contain 'fox': " + sentenceContainsFox);

Here’s the output:

Does the sentence contain ‘fox’: false

Very interesting! This happens because Java is case sensitive when it deals with String s. This means that uppercase and lowercase are not treated as equal, just like when you use variables names when coding!

The common way to ignore the case of your String is to send the whole String to lowercase, like so:

String sentence = "The quick brown Fox jumps over the lazy Dog." ; sentence = sentence. toLowerCase ( ) ; boolean sentenceContainsFox = sentence. contains ( "fox" ) ; System . out . println ( "Does the sentence contain 'fox': " + sentenceContainsFox ) ; String sentence = "The quick brown Fox jumps over the lazy Dog."; sentence = sentence.toLowerCase(); boolean sentenceContainsFox = sentence.contains("fox"); System.out.println("Does the sentence contain 'fox': " + sentenceContainsFox);

Matching Strings

Now sometimes we don’t need to worry about converting the entire String into lowercase to do checks. If you are checking to see if a particular String is equivalent to another String you could use the following methods:

equals()

This allows you to check if two String s are exactly equal.

String s1 = "fox" ; String s2 = "Fox" ; s1. equals ( s2 ) ; // will return false String s1 = "fox"; String s2 = "Fox"; s1.equals(s2); // will return false

equalsIgnoreCase()

This allows you to check if two String s are equal to each other while ignoring the case sensitivity.

String s1 = "fox" ; String s2 = "Fox" ; s1. equalsIgnoreCase ( s2 ) ; // will return true String s1 = "fox"; String s2 = "Fox"; s1.equalsIgnoreCase(s2); // will return true

An example of what the equals() method comes in handy, is when you need to validate a user’s password when they login. You need to ensure that the case matches exactly with the password. Whereas with the username, you don’t care as much with respect to case, so you would use the equalsIgnoreCase() when validating their username.

Note: Just remember never to compare two String s using the ‘==’ operator, as this compares the memory address of the actual String instead of comparing the actual contents of the String .

Substring

Another useful method is the substring() method. This allows you to deconstruct a piece of a String based on an index. What the heck does that mean!? Here’s an example to make things clearer:

String aString = "This is a sentence that will be deconstructed with the substring method" ; String aNewString = null ; // substring takes two parameters, a beginning index and an ending index // it will construct a new String based on these indices aNewString = aString. substring ( 8 , 45 ) ; System . out . println ( aNewString ) ; String aString = "This is a sentence that will be deconstructed with the substring method"; String aNewString = null; // substring takes two parameters, a beginning index and an ending index // it will construct a new String based on these indices aNewString = aString.substring(8, 45); System.out.println(aNewString);

This will output:

a sentence that will be deconstructed

You see what happened there? The “aNewString” String is made up of the 8th character all the way to the 45th character of the old String (“aString”).

Try it Yourself

Open your STS IDE and create a String . Then type in the variable name that you assigned to your String and hit DOT (.), you’ll see the list of methods that you can call popup in the auto-complete popup box. In this list you’ll see things like startsWith() and replace() . Read up on what they do and test them out for yourself, it’s the best way to learn what you can do with String manipulation.

Thanks Everyone

Thanks again for reading yet another Java tutorial on my How to Program with Java blog! I hope you’re still excited to learn Java and are looking forward to more tutorials in the future… if there’s a topic you’d like me to cover, feel free to leave it in the comments below, I’d love to hear what you guys want to learn about 🙂

Happy learning everyone!