简体   繁体   中英

Splitting string data in java with white spaces

I have a string xyz az . How to split it into xyz az . That is splitting the string into two parts taking first white space as the split point. Thanks

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

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

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 az , you will still have to get rid of that one more space between az

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM