How to Split a string using String.split()? Understanding the Java Split String Method. Let’s get started.
Java StringTokenizer:
In Java, the string tokenizer class allows an application to break a string into tokens. The tokenization method is much simpler than the one used by the StreamTokenizer
class. The StringTokenizer
methods do not distinguish among identifiers, numbers, and quoted strings, nor do they recognize and skip comments.
Java String Split:
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split
method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
If you want to split by new line
then you could use below:
1 |
String lines[] = String.split("\\r?\\n"); |
There’s only two newlines
(UNIX and Windows) that you need to worry about.
Other must read:
- https://crunchify.com/write-java-program-to-print-fibonacci-series-upto-n-number/
- List of more than 100 Java Tutorial
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 |
package com.crunchify; import java.util.StringTokenizer; /** * @author Crunchify.com * */ public class CrunchifyStringTokenizerAndSplit { public static void main(String[] args) { String delims = ","; String splitString = "one,two,,three,four,,five"; System.out.println("StringTokenizer Example: \n"); StringTokenizer st = new StringTokenizer(splitString, delims); while (st.hasMoreElements()) { System.out.println("StringTokenizer Output: " + st.nextElement()); } System.out.println("\n\nSplit Example: \n"); String[] tokens = splitString.split(delims); int tokenCount = tokens.length; for (int j = 0; j < tokenCount; j++) { System.out.println("Split Output: "+ tokens[j]); } } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
StringTokenizer Example: StringTokenizer Output: one StringTokenizer Output: two StringTokenizer Output: three StringTokenizer Output: four StringTokenizer Output: five Split Example: Split Output: one Split Output: two Split Output: Split Output: three Split Output: four Split Output: Split Output: five |