There are various ways in which we can split a String in Java, but the most efficient way is making use of regular expressions.
If you have a String that you want to split on dot (.), then you can write you code as follows,
package org.code2care.example;
public class JavaSplitOnDotStringExample {
public static void main(String[] args) {
String sentence = "This is sentence one. This is sentence two";
String[] splittedStringArray = sentence.split("\\.\\s");
for (String string : splittedStringArray) {
System.out.println(string);
}
}
}
Output:
We have made use of the split() function from the java.lang.String class
public String[] split(String regex)
Let's see another example with Pattern and Matcher classes from java.util.regex.
package org.code2care.example;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaSplitOnDotStringExample2 {
public static void main(String[] args) {
String sentence = "1.2.3.4.5.6.7.8";
Pattern pattern = Pattern.compile("(\\d+)");
Matcher matcher = pattern.matcher(sentence);
//Print them out
while (matcher.find()) {
String splittedString = matcher.group(1);
System.out.print(splittedString+"\t");
}
}
}
Output:
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!