【发布时间】:2017-11-16 13:38:22
【问题描述】:
我需要帮助创建一个拆分字符串的循环。到目前为止,我有下面的代码。
System.out.println("*FILE HAS BEEN LOCATED*");
System.out.println("*File contains: \n");
List<String> lines = new ArrayList<String>();
while (scan.hasNextLine())
{
lines.add(scan.nextLine());
}
String[] arr = lines.toArray(new String[0]);
String str_array = Arrays.toString(arr);
String[] arraysplit;
arraysplit = str_array.split(":");
for (int i=0; i<arraysplit.length; i++)
{
arraysplit[i] = arr[i].trim();
System.out.println(arr[i]);
}
其中一个字符串的示例是
Firstname : Lastname : age
我希望它将字符串拆分为另一个数组,如下所示:
Firstname
Lastname
age
我在运行代码时仍然遇到错误,好像当我将数组转换为字符串时,它会在字符串中放入逗号,因此在我尝试将字符串拆分时会导致问题 : not ,
【问题讨论】:
-
还有什么问题?
-
会不会是你把事情弄得太复杂了?
"Firstname : Lastname : age".split("\\s*:\\s*")应该会给你想要的结果。 -
这个问题仍然毫无意义。 You 调用
Arrays.toString(arr),它使用,作为分隔符清楚且明显地将每个数组项写入一个字符串,但您希望它的行为不像它那样记录在案。为什么?
标签: java arrays string list split