我有一个字符串(从文件中获取):
Computer: intel, graphic card: Nvidia,
Mouse: razer, color: white etc.
我需要在“:”和“,”之间取单词。
当我这样做时
Scanner sc = new Scanner(new File(path));
String str = sc.nextLine();
ArrayList<String> list = new ArrayList<String>();
while (sc.hasNextLine()) {
for (int i = 0; i < str.length(); i++) {
list.add(str.substring(str.indexOf(":"), str.indexOf(",")));
}
System.out.println("test");
sc.nextLine();
}
我只采用“:intel”。 我不知道如何从同一行中获取更多单词以及从下一行中获取更多单词。
最佳答案
假设文件内容test.txt
如下:
Computer: intel, graphic card: Nvidia
Mouse: razer, color: white
下面的程序将
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
class Coddersclub {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("test.txt"));
ArrayList<String> list = new ArrayList<String>();
String str = "";
while (sc.hasNextLine()) {
str = sc.nextLine();
String[] specs = str.split(",");
for (String item : specs) {
list.add(item.substring(item.indexOf(":") + 1).trim());
}
}
System.out.println(list);
}
}
输出:
[intel, Nvidia, razer, white]
注意:如果您要查找的列表为 [: intel, : Nvidia, : razer, :white]
,请替换 list.add (item.substring(item.indexOf(":") + 1).trim());
与 list.add(item.substring(item.indexOf(":")).trim( ));
。
如果您正在寻找其他内容,请随时发表评论。
关于Java - 以特定方式切割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60338121/