0

For example, if I have a string "Hello how are you". After I use the split() to separate all the elements, I want to put "Hello" to a variable, also same as the remainings, which method should I use to do it as it is not an ArrayList so I can't use the index. Lots of thanks.

2 Answers2

1

You can achieve the same like this :-

String input = "Hello how are you";
String[] splittedString = input.split(" ");
System.out.println(splittedString[0]);
Siddharth
  • 2,046
  • 5
  • 26
  • 41
0

Can I put 2 items in the same string, like putting "how" and "are" together in a new variable?

You can use String.split(String, int) (where the second argument is a limit). Something like

String str = "Hello how are you";
String[] parts = str.split("\\s+", 2);
System.out.printf("First Word: %s%n", parts[0]);
System.out.printf("Rest of the Words: %s%n", parts[1]);

Outputs (as requested)

First Word: Hello
Rest of the Words: how are you
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249