I have a string xyz a z. How to split it into xyz az. That is splitting the string into two parts taking first white space as the split point. Thanks
-
1Could you share your thoughts on how you'd go about it?devnull– devnull2014-01-17 06:59:09 +00:00Commented Jan 17, 2014 at 6:59
-
you mean to loop through the string, and for each character check if its first space, if first white space is found store in one string and remaining in another by concatenating ?user1002448– user10024482014-01-17 07:03:28 +00:00Commented Jan 17, 2014 at 7:03
-
1@user1002448 - split splits the entire String based on whitespaces... I was asking you to split it first, take out the first element, add a whitespace and add the remaining elements ... I think kapep's answer is the one you should look at.TheLostMind– TheLostMind2014-01-17 07:06:33 +00:00Commented Jan 17, 2014 at 7:06
Add a comment
|
6 Answers
Use String.split with the second limit parameter. Use a limit of 2.
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times
2 Comments
Keerthivasan
Will this split the string only once with delimiter as whitespace?
kapex
@Octopus yes, it will split the string only once, at the first occurence of the delimiter.
Try this
String givenString = "xyz a z";
String[] split = givenString.split(" ");
StringBuffer secondPart = new StringBuffer();
for (int i = 1; i < split.length; i++) {
secondPart.append(split[i]);
}
StringBuffer finalPart = new StringBuffer();
finalPart.append(split[0]);
finalPart.append(" ");
finalPart.append(secondPart.toString());
System.out.println(finalPart.toString());
Comments
Do like this
public static void main(String []args){
String a= "xyz a z";
String[] str_array=a.split(" ");
System.out.print(str_array[0]+" ");
System.out.println(str_array[1]+str_array[2]);
}
1 Comment
TheLostMind
It will show xyz on one line and az on another... use print with " "
Try this
String Str = new String("xyz a z");
for (String retval: Str.split(" ", 2)){
System.out.println(retval);
2 Comments
Venkatesh K
Second parameter in split method decides
gowtham
Good, but forgot to remove space between a and z in second element
Try this
String path="XYZ a z";
String arr[] = path.split(" ",2);
String Str = new String("xyz a z");
for(int i=0;i<arr.length;i++)
arr[i] = arr[i].replace(" ","").trim();
StringBuilder builder = new StringBuilder();
for(String s : arr) {
builder.append(s);
builder.append(" ");
}
System.out.println(builder.toString());
In the for loop you can append a space between two arrays using builder.append(" ").