14

I have a method which will return two strings in an array, split(str, ":", 2) to be precise.

Is there a quicker way in java to assign the two values in the array to string variables than

String[] strings = str.split(":", 2);
String string1 = strings[0];
String string2 = strings[1];

For example is there a syntax like

String<string1, string2> = str.split(":", 2);

Thanks in advance.

2
  • Nothing comes to mind immediately. However, I wonder what the need is to assign it to these names, and if you couldn't set it up with two functions. The first function could get the first part of the String, and the second the second part of the String. Is there a reason to do this beyond clarity? Commented Sep 8, 2012 at 5:47
  • Nope, no reason beyond clarity. Commented Sep 8, 2012 at 5:56

3 Answers 3

11

No, there is no such syntax in Java.

However, some other languages have such syntax. Examples include Python's tuple unpacking, and pattern matching in many functional languages. For example, in Python you can write

 string1, string2 = text.split(':', 2)
 # Use string1 and string2

or in F# you can write

 match text.Split([| ':' |], 2) with
 | [string1, string2] -> (* Some code that uses string1 and string2 *)
 | _ -> (* Throw an exception or otherwise handle the case of text having no colon *)
Sign up to request clarification or add additional context in comments.

1 Comment

In PHP you can do list($foo,$bar,$baz) = array("fred","barney","wilma"); and get back foo="fred", bar="barney", etc. Handy for split functions with columnar data.
1

You can create a holder class :

public class Holder<L, R> {
    private L left;
    private R right;

   // create a constructor with left and right
}

Then you can do :

Holder<String, String> holder = new Holder(strings[0], strings[1]);

Comments

-6

I can say "Use Loops". May be for loops, may be while, that depends on you. If you do so, you don't have to worry about the array size. Once you have passed the array size as the "termination condition" it will work smoothly.

UPDATE:

I will use a code like below. I didn't runt it anyway, but I use this style always.

String[] strings = str.split(":", 2);

List keepStrings = new ArrayList();

for(int i=0;i<strings.length;i++)
{
    String string = strings[i];

    keepStrings.add(string);


}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.