![Java Example – Split String Into Array in Java](https://www.codebind.com/wp-content/uploads/2017/09/Java-Example-–-Split-String-Into-Array-in-Java.png)
In this example we will see How to Split String Into Array in Java. The Java String split Example shown below describes how Java String is split into multiple Java String objects and assign them to an array.
Java String class defines following methods to split Java String object.
String[] split
( String regularExpression ) – Splits the string according to given regular expression.String[] split
( String reularExpression, int limit ) – Splits the string according to given regular expression. The number of resultant sub-strings by splitting the string is controlled by limit argument.
/** * Java String Split Example */ public class JavaStringSplitExample { public static void main(String args[]) { /* String to split. */ String stringToSplit = "str1-str2-str3"; String[] tempArray; /* delimiter */ String delimiter = "-"; /* given string will be split by the argument delimiter provided. */ tempArray = stringToSplit.split(delimiter); /* print substrings */ for (int i = 0; i < tempArray.length; i++) System.out.println(tempArray[i]); /* NOTE : Some special characters need to be escaped while providing them as delimiters e.g. "." and "|" etc. */ System.out.println(""); stringToSplit = "str1.str2.str3"; delimiter = "\\."; tempArray = stringToSplit.split(delimiter); for (int i = 0; i < tempArray.length; i++) System.out.println(tempArray[i]); /* Using second argument in the String.split() method, we can control the maximum number of substrings generated by splitting a string. */ System.out.println(""); tempArray = stringToSplit.split(delimiter, 2); for (int i = 0; i < tempArray.length; i++) System.out.println(tempArray[i]); } } /* Output: str1 str2 str3 str1 str2 str3 str1 str2.str3 */
Leave a Reply