Question

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

Was it helpful?

Solution 2

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());

OTHER TIPS

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

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]);

     }

Try this

  String Str = new String("xyz a z");
    for (String retval: Str.split(" ", 2)){
     System.out.println(retval);

You need to use String.split with limit of 2 as it will be applied (n-1) times, in your case (2-1 = 1 ) time

So it will consider first space only.

But still you will get the result as xyz and a z, you will still have to get rid of that one more space between a z

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(" ").

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top