≡ Menu

String Manipulation

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("http://howtoprogramwithjava.com/reviews/");
websites.add("http://howtoprogramwithjava.com/programming-101-the-5-basic-concepts-of-any-programming-language/");
websites.add("http://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:

  1. "howtoprogramwithjava.com", "reviews"
  2. "howtoprogramwithjava.com", "programming-101-the-5-basic-concepts-of-any-programming-language"
  3. "howtoprogramwithjava.com" ,"consulting", "web-application-development"
  4. "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 Strings 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 Strings. 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
}

This code will split the Strings 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:

String Manipulation

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);

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);

Here’s the output:

Does the sentence contain ‘fox': false

Very interesting! This happens because Java is case sensitive when it deals with Strings. 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);

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 Strings are exactly equal.

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

equalsIgnoreCase()

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

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 Strings 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);

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!

{ 2 comments… add one }

  • Durim April 18, 2013, 12:35 am

    Thank you so much Trevor!
    I learned a lot from this tutorial:D

  • 1eye May 11, 2013, 11:36 pm

    Great stuff, I am interested in ;earning about remote connectivity to remote databases and how to utilize images to retrieve data web and android project I am trying. Start big or go home. I have not been able to leave my computer since I found your tutorials. I hope to master the art of programming……Thank You for the great info. I am sure I will hit the ground running :)

Leave a Comment

Powered by sweet Captcha

Next post:

Previous post: