How to Convert String to Array in Java [2021]
In today's programming world, We generally need to Convert String to Array in Java, In this tutorial, we will cover how to convert String to Array in Java using two approaches.
- Using the Split method of String class.
- Using the Pattern class compile method with regular expression.
Earlier we have covered different conversion like Convert to String from Byte Array In Java, Convert String to Byte Array in Java and Convert Between Java Byte Array to Object In Java which is also similar to our current requirement.
Let's dive in for our current tutorial...
How to Convert String to Array in Java
1. Using the Split method of String class.
How to convert String to Array in Java Using Split method |
The split method is used to split the string around the regular expression passed. The split method will convert sampleString "Java Code Geek" to three separate Array Elements Java Code Geek.
public class StringToArrayUsingSplit {
public static void main(String[] args) {
String sampleString = "Java Code Geek";
String[] splitedString= sampleString.split(" ");
for (String indexValue : splitedString) {
System.out.println(indexValue);
}
}
}
Output:
Java
Code
Geek
2. Using the Pattern class compile method with regular expression.
How to Convert String to Array in Java Using Pattern Compile method |
Pattern class has a split method which also converts String to array in java.
import java.util.regex.Pattern;
public class StringToArrayUsingPatternCompile {
public static void main(String[] args) {
String sampleString = "Java Code Geek";
Pattern pattern = Pattern.compile(" ");
String[] array = pattern.split(sampleString);
for (String indexValue : array) {
System.out.println(indexValue);
}
}
}
Output:
Java
Code
Geek
Conclusion:
In this tutorial, we have covered how to convert String to Array in Java using two strategies
- Using the Split method of String class.
- Using the Pattern class compile method with regular expression.
Thanks for reading this tutorial so far. If you like this tutorial then please share it with your friends and colleagues. If you have any questions, doubts, suggestions, or feedback then please drop a comment and I'll try to answer your question.
So what do you think about this simple process to Convert String to Array In Java? It's Easy Right?
Happy Learning!!!
More Examples you may like
Comments
Post a Comment
If you have any doubts, Please let me know.