Question

I have read a lot but I am not getting how to get my required String,My String is: "552 s East and west we are the best" I want to get "552" in one string "s" in char and all the remaining String after the space 's' in one String,and the position of spaces will be changed every time.Please help.I have tried

 messages="552 s East and west we are the best";
    String[] sp=messages.split(" ");
         String threadid=sp[0];
         String status=sp[1];
         String msg=sp.toString();

but I am getting something garbage in msg.

Was it helpful?

Solution

You can try this

    String str = "552 s East and west we are the best";
    String[] arr = str.split(" ", 3);
    String partOne = arr[0];
    char partTwo = arr[1].charAt(0);
    String partThree = arr[2];

    System.out.println("part one: "+partOne);
    System.out.println("part two: "+partTwo);
    System.out.println("part three: "+partThree);

Out put:

 part one: 552
 part two: s
 part three: East and west we are the best

OTHER TIPS

Two options:

Try this way

public class test1 {
    public static void main(String args[]) throws NumberFormatException, IOException
    {
    String x="552 s East and west we are the best";
    String x1[]=x.split(" ",2);
    System.out.println(x1[0]);
    System.out.println(x1[1]);

    }
}

There would be many way to get it done.One may be doing sub string your input string by index,
Other may be -

String[] splts = inputString.split("\\s",3);
int number = Integer.parseInt(splts[0]);
String s = splts[1];
String others = splts[2];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top