Learn Java – How to Split a String?

java split string

If you are looking to learn how to split a string in Java, you have come to the right place. String operations are the most common operations when it comes to programming. Java Strings are no different and will be used in almost every program you write.

To split a string in Java, you need to use the String.split() method that is readily available to the Java programmer. Let’s see an example to get a better idea.

The main method that does the job is the split() method. The method takes regex as an argument. Regex is great. However, they can be complex to use. With regex, you need to take care of the escape characters. Let’s learn more about it below.

ENJOYING THIS POST?

Get More Benefits With LiveEdu Pro

Escape characters: There are many escape characters in the Java programming language. For example, dot(.) or backslash(\), etc.

To handle the escape character, you can either choose to create a special regex for the operation, or you can use Pattern.quote() function to escape the character. Let’s see an example below to understand the whole picture.

String with a dot

As mentioned earlier, you can choose to use the Pattern.quote() method or use the traditional escape method of using a double backslash(\\). Let’s see both of them live in the code below.

Filename: DotSplit.java

Output

Alternative Ways

There are many other ways to split the string. One way is to use the StringTokenizer class. StringTokenizer class is a legacy class and should be used with caution.

Putting necessary test cases

Before you want to split a string according to a particular character, it is advisable to test whether it appears i n the string. You can do so by using the contains() method.

The logic goes as below:

And, that’s the end of the tutorial. If you have any other questions, don’t forget to comment below and let us know.

You can also check on our website for videos about Java. Below are some examples:

  • Lambda expression refactoring (part 1) – Java

  • New Metroid: 2D Game Developing (part 5) – Java

You can also follow some of our broadcasters who program in Java as below:

 chase1263070

 Ankira

Another cool way to find out interesting things about Java is to access our project page!

LiveEdu Pro
Check Out the LiveEdu Pro Subscription

  • João Santos

    Good subject. I hope you also do a tutorial like this for Ruby.

Read previous post:
fire-ice-100647942-large
2017编程趋势预测:哪些技术大热?哪些技术遇冷?

程序员们喜欢嘲笑时装界的潮流总是变化得像一阵风一样。这与编程界的潮流趋势是不一样的,因为在技术世界,流行的是严谨,科学,数学和精确的准则。这不是说编程是一种缺乏趋势的行业。不同的是,编程的趋势是由更高效率,改良的用户化和使用方便来驱动的。这些可以带来更多便利的新技术让前一代技术黯然失色。这是一种知识界的精华,而不是异想天开。

Close