简体   繁体   中英

How do I set array arguments into variables using Java

I want to take this string "John Doe and Eli Manning", and using split() on the String to store the elements of the array into variables.

I already know how to do the first part

String str = "John Doe and Eli Manning"; 
String tokens[] = str.split("and");

Now I have an array ["Kevin Suffredini", "Eli Manning"]. I want to set those two elements into separate variables that I can use. What is the syntax for this?

something like?? :

String person1 = ...arg[0];
String person2 = ...arg[1];

Use the tokens array you defined, like

String p1 = tokens[0];
String p2 = tokens[1];

You probably want to make sure your tokens array has 2 items in it.

Also, you can't dynamically create variables if you can have an arbitrary amount tokens, but you can loop over tokens and get each String in the array.

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