Java—为单个变量分配数组值的快速方法
我有一个方法,它将在一个数组中返回两个字符串,准确地说,Java—为单个变量分配数组值的快速方法,java,arrays,syntax,variable-assignment,Java,Arrays,Syntax,Variable Assignment,我有一个方法,它将在一个数组中返回两个字符串,准确地说,split(str,“:”,2) 在java中,有没有比指定字符串变量更快的方法将数组中的两个值指定给字符串变量 String[] strings = str.split(":", 2); String string1 = strings[0]; String string2 = strings[1]; 例如,有这样的语法吗 String<string1, string2> = str.split(":", 2); Stri
split(str,“:”,2)
在java中,有没有比指定字符串变量更快的方法将数组中的两个值指定给字符串变量
String[] strings = str.split(":", 2);
String string1 = strings[0];
String string2 = strings[1];
例如,有这样的语法吗
String<string1, string2> = str.split(":", 2);
String=str.split(“:”,2);
提前谢谢。我可以说“使用循环”。可能是循环,可能是while,这取决于你。如果这样做,就不必担心数组大小。一旦将数组大小作为“终止条件”传递,它将顺利工作
更新:
我将使用下面这样的代码。我没有跑,但我总是用这种风格
String[]strings=str.split(“:”,2)
List keepStrings=new ArrayList();
对于(int i=0;i您可以创建holder类:
public class Holder<L, R> {
private L left;
private R right;
// create a constructor with left and right
}
公共类持有者{
列兵L左;
私权;
//创建一个具有左键和右键的构造函数
}
然后你可以做:
Holder<String, String> holder = new Holder(strings[0], strings[1]);
Holder Holder=新的Holder(字符串[0],字符串[1]);
不,Java中没有这种语法
然而,其他一些语言也有这样的语法。例如Python的元组解包和许多函数式语言中的模式匹配。例如,在Python中,您可以编写
string1, string2 = text.split(':', 2)
# Use string1 and string2
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 *)
或者用F#你可以写
string1, string2 = text.split(':', 2)
# Use string1 and string2
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 *)
没有什么会立即浮现在脑海中。但是,我想知道需要将它分配给这些名称,如果你不能用两个函数设置它,那么需要做什么。第一个函数可以获取字符串的第一部分,第二个函数可以获取字符串的第二部分。有没有超出清晰性的原因?没有,没有超出清晰性的原因。在PHP中,你可以执行list($foo,$bar,$baz)=数组(“fred”、“barney”、“wilma”);
并返回foo=“fred”、bar=“barney”等。便于使用列数据拆分函数。