I have
String a="4:1 6:24 8:3 10:44 20:4 23:5 28:6"
How can I replace all characters after :
?
In the end, I want a="4;6;8;10;20;23;28;"
I only know how to do with one
a.substring(0, a.indexOf(":")).trim() ";"
But this code only replaces all data after :
CodePudding user response:
This should help
String a = "4:1 6:24 8:3 10:44 20:4 23:5 28:6";
String b = a.replaceAll(":[0-9]*[ ]?",";");
System.out.println(b);
Output
4;6;8;10;20;23;28;
CodePudding user response:
You can use stream API to achieve that.
String a="4:1 6:24 8:3 10:44 20:4 23:5 28:6";
String result = Arrays.stream(a.split(" "))
.map(s -> s.split(":")[0])
.collect(Collectors.joining(";"));
System.out.println(result);
Output
4;6;8;10;20;23;28
Explanation
a.split(" ")
will split string into tokens where delimiter is spacemap(s -> s.split(":")[0])
will take every token, splits it on:
and return only first partcollect(Collectors.joining(";"))
will join all tokens using field separator;