+ 3
java split not working
why did the split function didn't work? did i do something wrong on the syntax? https://code.sololearn.com/c1Ss2gaq7AZQ/?ref=app
5 ответов
+ 7
lvl 1 crook It's likely more to do with Regex than with Java. In regular expressions, the dot (".") is a special character that matches on all characters.
To match on the dot character, the dot must either be escaped or placed within character brackets.
+ 5
lvl 1 crook
Regex , I don't know anything about it 😶
I just typed this in google "java split by dot"
And this came up
https://stackoverflow.com/questions/14833008/java-string-split-with-dot
Just change str.split(".");
By
str.split("\\.");
And it works 😅
edit:
https://code.sololearn.com/W0pNLQ8bef6J/?ref=app
+ 5
You can also use:
str.split("[.]");
+ 4
Splitting text: RegEx
import java.util.regex.Pattern;
//import java.util.regex.*;
class SplittingText
{
public static void main(String...regex){
Pattern p = Pattern.compile(".\\s");
String[] fields = p.split(
"Follow. One. Course. Until. Success");
/* OR
If you want to exclude a space after
words, you can use:
Pattern p = Pattern.compile("\\.");
String[] fields = p.split(
"Follow.One.Course.Until.Success");
*/
int len = fields.length;
for (int i = 0; i < len; i++)
System.out.println(fields[i]);
}
}
+ 3
thx 🇮🇳Omkar🕉 //Busy , Exams.
David Carroll
it finally works, i'm guessing a dot is taken as a special character in java so it needs to be cancelled out with backslashes.