If you want to split a string in Java? then this question is for you as I have shared how to split string using Java programming language.
Just use the appropriate method: String#split().
1 2 3 4 | String string = "004-034556"; String[] parts = string.split("-"); String part1 = parts[0]; // 004 String part2 = parts[1]; // 034556 |
You can split a String by space using the split() function of java.lang.String class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | public class StringSplitExample { public static void main(String args[]) { // Suppose we have a String with currencies separated by space String lineOfCurrencies = "USD JPY AUD SGD HKD CAD CHF GBP EURO INR"; // we use regex " ", which will match just one whitespace String[] currencies = lineOfCurrencies.split(" "); System.out.println("input string words separated by whitespace: " + lineOfCurrencies); System.out.println("output string: " + Arrays.toString(currencies)); String lineOfPhonesWithMultipleWhiteSpace = "iPhone Galaxy Lumia"; String[] phones = lineOfPhonesWithMultipleWhiteSpace.split("\\s+"); System.out.println("input string separted by tabs: " + lineOfPhonesWithMultipleWhiteSpace); System.out.println("output string: " + Arrays.toString(phones)); String linewithLeadingAndTrallingWhiteSpace = " Java C++ "; String[] languages = linewithLeadingAndTrallingWhiteSpace.split("\\s+"); System.out.println("input string with leading and traling space: " + linewithLeadingAndTrallingWhiteSpace); System.out.println("output string: " + Arrays.toString(languages)); // splitting it i.e. call trim() before split() as shown below languages = linewithLeadingAndTrallingWhiteSpace.trim().split("\\s+"); System.out.println("input string: " + linewithLeadingAndTrallingWhiteSpace); System.out.println("output string afte trim() and split: " + Arrays.toString(languages)); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.