Reputation: 37
I have string like "abc /123 /456"
and I want to split it into two stings: "abc 123"
and "abc 456"
.
I tried:
String[] str = MESSAGE.split("/")
But didn't provide required result. Could anyone, please, share any ideas with me how to perform it?
Upvotes: 0
Views: 94
Reputation: 18588
You will need to add a little logic after splitting the String
.
This is how I would do it:
String s = "abc /123 /456"; String[] partsOfS = s.split("/"); String prefix = partsOfS[0];
for (int i = 1; i < partsOfS.length; i++) {
System.out.println(prefix + partsOfS[i]);
}
EDIT
For the case of the prefix not separated by /
from the other parts of the String
but only by space, you will probably need a second split and a second loop, like this:
String s = "abc 123/ 456/";
String[] splitBySpace = s.split(" ");
String prefix = splitBySpace[0];
String[] partsOfS = new String[splitBySpace.length - 1];
for (int i = 1; i < splitBySpace.length; i++) {
partsOfS[i - 1] = splitBySpace[i].replace("/", "");
}
for (int i = 0; i < partsOfS.length; i++) {
System.out.println(prefix + " " + partsOfS[i]);
}
There may be better solutions concerning performance and programming style, but this is working with your example String
from the comment.
Upvotes: 0
Reputation: 643
you did just fine when deciding to split it , after that you should concat the first element of the splited array with all the other elements to achieve what you want.
here's some code to make it clearer.
public class main {
public static void main(String[] args) {
String MESSAGE = "abc /123 /456";
String[] str = MESSAGE.split("/") ;
String[] str2 = new String[str.length-1];
System.out.println(str[0]);
for ( int i=1 ; i<str.length ; i++) {
str2[i-1] = str[0]+str[i];
}
for ( int i=0 ; i<str2.length ; i++) {
System.out.println(str2[i]);
}
}
}
Upvotes: 1
Reputation: 236132
Just stick the pieces together in any way you need, like this:
String[] str = MESSAGE.split(" /");
String s1 = str[0] + " " + str[1];
String s2 = str[0] + " " + str[2];
Also notice that it'd be better to split the string using as pattern " /"
, that is, with a space before the slash.
Upvotes: 2