+ 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

1st Nov 2019, 2:39 AM
Shen Bapiro
Shen Bapiro - avatar
5 odpowiedzi
+ 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.
1st Nov 2019, 3:33 AM
David Carroll
David Carroll - avatar
+ 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
1st Nov 2019, 3:02 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 5
You can also use: str.split("[.]");
1st Nov 2019, 3:03 AM
David Carroll
David Carroll - avatar
+ 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]); } }
1st Nov 2019, 7:10 AM
Danijel Ivanović
Danijel Ivanović - avatar
+ 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.
1st Nov 2019, 3:09 AM
Shen Bapiro
Shen Bapiro - avatar