Java

How to Parse a String in Java

In the Java language, strings are objects that represent a character sequence. Also, string objects are immutable, so they cannot be updated after their creation. However, you can parse them by dividing the string to get the specific part of the string, which is considered a token.

This blog will explain how to parse a string in Java. Let’s start!

Parse a String in Java

In Java, there exist three main approaches to parse a string:

  • Parse string by using Java Split() method
  • Parse string by using Java Scanner class
  • Parse string by using StringUtils class

We will now discuss each of the above-mentioned approaches in detail.

Method 1: Parse String by Using Java split() Method

In Java, there is a split() method of the String class that splits the given string and returns the array of substrings. It keeps the given string unchanged. Also, the split() method is case-sensitive.

The split() method has two variations.

  • split(regular-expression/delimiter)
  • split(regular-expression/delimiter, limit)

Have a look at the given examples to know more about the usage of the split() method.

Example 1: Parsing String in Java Using split(regular-expression/delimiter) variant
In this example, we will use the split(regular-expression/delimiter) variant of the split() method. A regular expression is passed as an argument for this method. If the given expression matches the string, it will divide the string; otherwise, it will print out the whole string.

Here, we have a string named stg:

String stg = "Practice makes man perfect!";

While using the split() method, you can also use different delimiters as a condition, such as any alphabet from string or special character, and many more. The below-given string will be split based on the white spaces:

String[] spStg = stg.split(" ");

Lastly, for printing the parsed string, use for loop:

for (String i: spStg) {
      System.out.println(i);
    }

As you can see, the split() method has successfully parsed the given string based on the occurrence of the white spaces:

Example 2: Parsing String in Java Using split(regular-expression/delimiter, limit) variant
This variant works almost the same as the above. Here, we will add the limit with a delimiter, which determines the number of splitting strings according to the string length.

For instance, we have a string named stg:

String stg = "Practice makes man perfect!";

We will use for loop to split the whole stg string with white space as delimiter and limit as 3:

for(String splits:stg.split(" ",3)) {
    System.out.println(splits);
}

The specified string will split as the space occurs, and it will return three strings according to the added limit:

Method 2: Parse String by Using Java Scanner Class

To parse a string, Java Scanner class commonly uses a regular expression or regex. It divides the given string into tokens by using a useDelimiter() method.

Example
First, we have a string stng that needs to be parsed:

String stng = "Practice: makes man perfect!";

Create an object of the Scanner class and pass the string stng as a parameter:

Scanner scaner = new Scanner(stng);

The delimiter pattern is set using the useDelimiter() method of the Scanner class. Here, we will pass the colon “:” as a delimiter pattern in the useDelimiter() method:

scaner.useDelimiter(":");

This method splits the string when it finds a colon. To obtain all of the tokens in the string, use the hasNext() method in a while loop and print the result:

while (scaner.hasNext()){
       System.out.println(scaner.next());
}

Output

Method 3: Parse String by Using StringUtils Class

In order to parse a string using StringUtils class, first of all, we will create a maven project rather than a simple Java project and then add dependencies to it.

Here, we have specified maven dependency for adding StringUtils library in our XML file:

<dependencies>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.11</version>
    </dependency>
</dependencies>

Then, create a Java file, and use the StringUtils class to parse the string stng:

String stng = "Practice: makes man perfect!";

We will use the substringsBetween() method of StringUtils class, specify the stng string and pass “:” and “!” as delimiters which means that the resultant value will contain the substring that is present in between these two delimiters:

String[] stngArray = StringUtils. substringsBetween(stng, ":", "!");

To print the parsed strings, utilize for loop:

for (String i : stngArray) {
    System.out.println(i);
}

The output will display the substring between “:” and “!” delimiters:

We have provided the information related to parsing a string in Java.

Conclusion

To parse a string in Java, you can use the Java String split() method, Java Scanner class, or StringUtils class. For parsing a string based on the specified condition, these methods use delimiters to split the string. However, the split() method is majorly utilized as it supports adding delimiter/ regex and the relative limit. This blog explained the methods to parse a string in Java with examples.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.