-4

I have a String like the following 2 4 12 12 yellow Hi how are you

I want to split the string like this {2,2,12,12,yellow, Hi how are you} in order to pass the items in the list as parameters in a constructor.

Any help?

Josef Ginerman
  • 1,460
  • 13
  • 24
  • 2
    Well, `String.split`. But it's not obvious why `Hi how are you` should be a single string. – Andy Turner Feb 03 '19 at 12:06
  • 1
    I know String.split(" "), but I need to store it in an array list like this way because I have a Note class where 2 and 4 represents x and y coordinates, 12 and 12 represents width and height, yellow represents color and hi how are you represent a message. When I create a new Note class it should be like this Note note = new Note(x,y,width,height,color,message); and then add it to an array list – Issa Asbah Feb 03 '19 at 12:08
  • `split(" ")` isn't the only way to split a string. Perhaps take a look at the documentation of `String` to see alternative ways. – Andy Turner Feb 03 '19 at 12:12
  • 4
    I figured it out. I used split(" ", 6) which means limit on the 6 whitespace. – Issa Asbah Feb 03 '19 at 12:17

1 Answers1

0

The trivial answer is to split the string:

String[] fragments = theString.split(" ", 6);

Given that the fragments have specific meanings (and presumably you want some of them as non-string types), it might be more readable to use a Scanner:

Scanner sc = new Scanner(theString);
int x = sc.nextInt();
int y = sc.nextInt();
int width = sc.nextInt();
int height = sc.nextInt();
String color = sc.next();
String message = sc.nextLine();

This approach is also easier if you are reading these strings, say, from a file or standard input: just create the Scanner over the FileReader/InputStream instead.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243