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.
Asked
Active
Viewed 253 times
0

Hui Ting Ko
- 51
- 7
-
Using `String.split()` will already put each word into an array variable. What are you trying to accomplish? – Tim Biegeleisen May 05 '16 at 01:59
-
What do you mean by "also same as the remainings"? – Elliott Frisch May 05 '16 at 02:06
-
@ElliottFrisch Can I put 2 items in the same string, like putting "how" and "are" together in the same variable? – Hui Ting Ko May 05 '16 at 02:16
2 Answers
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
-
Can I put 2 items in the same string, like putting "how" and "are" together in a new variable? – Hui Ting Ko May 05 '16 at 02:10
-
-
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