+ 1

Split string Java. Please help!

Need to split string "New York 60 50 40 30" so it would be only integers part - "60 50 40 30"

6th Oct 2019, 1:15 PM
Ilja Veselov
Ilja Veselov - avatar
15 Respuestas
+ 7
Here's another solution similar to Denise Roßberg's👍🍻 String s = "New York 60 50 40 30"; String filtered = s.replaceAll("[^0-9]", " "); String[] numbers = filtered.split("\\s+"); for (String n : numbers) { System.out.println(n); }
6th Oct 2019, 10:19 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 7
Ilja Veselov Here is, with No space before integers: import java.util.regex.Pattern; import java.util.regex.Matcher; String s = "New York 60 50 40 30"; Pattern pattern = Pattern.compile("\\d+"); Matcher match = pattern.matcher(s); while (match.find()) { System.out.print(match.group() +" "); }
7th Oct 2019, 7:21 AM
Danijel Ivanović
Danijel Ivanović - avatar
+ 6
Ilja Veselov you can post the code you're struggling with — https://www.sololearn.com/post/75089/?ref=app
7th Oct 2019, 7:05 AM
Danijel Ivanović
Danijel Ivanović - avatar
+ 3
You can try something like this: String str = "New York 60 50 40 30"; str = str.replaceAll("[A-Za-z]", ""); System.out.println(str); Read more about regular expressions: https://www.vogella.com/tutorials/JavaRegularExpressions/article.html
6th Oct 2019, 5:06 PM
Denise Roßberg
Denise Roßberg - avatar
+ 2
import java.util.regex.Matcher; import java.util.regex.Pattern; ... Pattern pattern = Pattern.compile("\\d.+\\d"); Matcher matcher = pattern.matcher("New York 60 50 40 30"); String part = matcher.find() ? matcher.group() : ""; System.out.println( part );
6th Oct 2019, 5:07 PM
zemiak
+ 2
There also lessons about regular expressions here on sololearn: https://www.sololearn.com/learn/9704/?ref=app
6th Oct 2019, 5:22 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
Unfortunately this is not an answer to my question. Program is reading strings from a fila and I can't count chartAt index every time as all strings have different lengths . I have common pattern for all strings first location and then numbers so I need to split all strings to only numbes.
6th Oct 2019, 3:51 PM
Ilja Veselov
Ilja Veselov - avatar
+ 1
Will try
6th Oct 2019, 5:24 PM
Ilja Veselov
Ilja Veselov - avatar
+ 1
replaceAll method gives some spaces before integers it looks like : 60 50 40 30. Need no spaces before line.
6th Oct 2019, 6:28 PM
Ilja Veselov
Ilja Veselov - avatar
+ 1
Here is the solution replaceAll("\\p{L}+\\s","")
6th Oct 2019, 10:22 PM
Ilja Veselov
Ilja Veselov - avatar
+ 1
String s = "New York 60 50 40 30"; for(String t: s.split(" ")){ if(t.matches(".*\\d.*")){ System.out.println(t); } } // this way works as well if you want like this
7th Oct 2019, 2:58 AM
Ferhat Sevim
Ferhat Sevim - avatar
0
I know that it will be String.split, but how exactly?
6th Oct 2019, 2:45 PM
Ilja Veselov
Ilja Veselov - avatar