只获得一个数组中的名字
问题描述:
我有一个这样的数组列表:ArrayList names = new ArrayList <>();存储人们在不同教科书中输入的姓氏和名字。只获得一个数组中的名字
因此,当提示乔拜登是元素编号1,那么奥巴马将是数组列表中的元素编号2。我的问题是,如果只能从阵列中得到像Joe这样的名字而没有得到拜登呢?
答
是的,你可能只是做
names.get(0).split("\\s+")[0] //this would get you "Joe"
获得姓氏可能做
names.get(0).split("\\s+")[1] //this would get you "Biden"
这样完全依赖于事实,你在他们的姓和名之间有一个空格。并显然编辑0
到任何你想要的索引。
+0
工作正常!谢谢。 – aaaa
答
每个元素将作为一个String对象坐在ArrayList中。
您可以使用Str.split()将其拆分成数组并获取姓氏。
比方说,你的ArrayList
String str = names.get(0); //Joe Biden
String[] arr = str.split(" "); //this will create Array of String objects
System.out.println(arr[1]); will print Biden
使用这种方法不过要小心,它会不会与人与3名或一个名称的工作。具有一个名称的人将导致ArrayIndexOutOfBoundsException。名称不止一个的人会错误地输出他们的姓氏。
但是您可以通过克服这个问题,
int arrLength = arr.length;
if(arrLength > 0) {
System.out.println(arr[arrLength - 1]); //this will always print the last name, if the name isn't empty
}
是。但请告诉我们你现在如何填充'名称'(分享你当前的代码)。 –
yes'names.get(0).split(“\\ s +”)[0]'会给你想要的结果 – 3kings
String FN = txtFN.getText(); – aaaa