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.
First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable. Thus, in Java, all arrays are dynamically allocated.
Extract() is a very popular function that converts elements in an array into variables in their own right. Extract takes a minimum of one parameter, an array, and returns the number of elements extracted.
Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.
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 *)
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With