“约翰”,“ 100.00”,“ 200.00”
如何读取文本文件的内容,然后在引号下打印字符串。
输出应为 准100.00 200.00
String CUSTOMER, CURRENT, NEW;
Scanner sc = new Scanner(str);
sc.useDelimiter(",");
while(sc.hasNext()){
CUSTOMER = sc.next();
CURRENT = sc.next();
NEW = sc.next();
System.out.println("" + CUSTOMER + " " + CURRENT +
" " + NEW);
}
sc.close();
如何将标记与引号分开。我得到的上述代码的输出是这个 “ Jhon”“ 100.00”“ 200.00”
答案 0 :(得分:0)
您可以通过以下命令获得所需的输出:
public static void main(String[] args) {
Pattern p = Pattern.compile(".*?\\\"(.*?)\\\".*?");
Matcher m = p.matcher("\"John\",\"100.00\",\"200.00\"");
while (m.find()) {
System.out.println(m.group(1));
}
}
说明
.*? - anything
\\\" - quote (escaped)
(.*?) - anything (captured)
\\\" - another quote
.*? - anything
输出
John
100.00
200.00
答案 1 :(得分:0)
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
扫描仪还可以使用除空格以外的定界符。此示例从字符串中读取多个项目:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
因此,您可以避免在substring(1,len-1)和useDelimiter(\“,\”)中使用首尾加引号,并在内部加上3个符号。
String str = "\"John\",\"100.00\",\"200.00\"";
System.out.println(str);
String CUSTOMER, CURRENT, NEW;
Scanner sc = new Scanner(
str.substring(1,str.length()-1) // <--- here substring
);
sc.useDelimiter("\",\""); // <---- here your split: <token>","<token>
while(sc.hasNext()){
CUSTOMER = sc.next();
CURRENT = sc.next();
NEW = sc.next();
System.out.println("" + CUSTOMER + " " + CURRENT + " " + NEW);
}
sc.close();
答案 2 :(得分:0)
这是完成任务的另一种方法:
String line, customerName, currentVal, newVal;
try (Scanner sc = new Scanner(new File("salesrep.txt"))) {
while (sc.hasNextLine()) {
line = sc.nextLine().replace("\"", "");
//skip blank lines (if any)
if (line.equals("")) {
continue;
}
String[] lineData = line.split(",");
customerName = lineData[0];
currentVal = lineData[1]; // or: double currentVal = Double.parseDouble(lineData[1]);
newVal = lineData[2]; // or: double newVal = Double.parseDouble(lineData[2]);
System.out.println("" + customerName + " " + currentVal + " " + newVal);
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}