Java examples to convert a string into string array using String.split()
and java.util.regex.Pattern
.slipt() methods.
String blogName = "how to do in java"; String[] words = blogName.split(" "); //[how, to, do, in, java] Pattern pattern = Pattern.compile(" "); String[] words = pattern.split(blogName); //[how, to, do, in, java]
1. String -> String[]
1.1. Using String.split()
Use split() method to split a string into tokens by passing a delimiter (or regex) as method argument.
String names = "alex,brian,charles,david"; String[] namesArray = names.split(","); //[alex, brian, charles, david]
1.2. Using Pattern.split()
In Java, Pattern
is the compiled representation of a regular expression. Use Pattern.split() method to convert string to string array, and using the pattern as the delimiter.
String names = "alex,brian,charles,david"; Pattern pattern = Pattern.compile(","); String[] namesArray = pattern.split( names ); //[alex, brian, charles, david]
2. String[] -> String
Use String.join()
method to create a string from String array. You need to pass two method arguments i.e.
- delimiter – the delimiter that separates each element
- array elements – the elements to join together
The join() will then return a new string that is composed of the ‘array elements’ separated by the ‘delimiter’.
String[] tokens = {"How","To","Do","In","Java"}; String blogName1 = String.join("", tokens); //HowToDoInJava String blogName2 = String.join(" ", tokens); //How To Do In Java String blogName3 = String.join("-", tokens); //How-To-Do-In-Java
Drop me your questions in the comments section.
Happy Learning !!
Comments