2

Java中是否有内置方法来确定字符串是否以特定字符开头?如何仅将不以定义字符开头的行写入输出文件?

   try {
        File input = new File("input");
        File output = new File("output");
        Scanner sc = new Scanner(input);
        PrintWriter printer = new PrintWriter(output);
        while (sc.hasNextLine()) {
            String s = sc.nextLine();
            printer.write(s);
        }
        printer.flush();
    }
    catch (FileNotFoundException e) {
        System.err.println("File not found. Please scan in new file.");
    }
4

2 回答 2

1

内置检查角色是否存在。

while (sc.hasNextLine()) {
    String s = sc.nextLine();
    if (s.startsWith("?"))
        printer.write(s);
}

或者

while (sc.hasNextLine()) {
    String s = sc.nextLine();
    char c = s.charAt(0);
    if (c.matches('?'))
        printer.write(s);
}

编辑:根据您的评论:

int i;
char c;
String s;
while (sc.hasNextLine()) {
    s = sc.nextLine();
    c = ' ';
    i = 0;
    while (c.matches(' ')) {
        c = s.charAt(i);
        if (c.matches('?'))
            printer.write(s);
        i++;
    }
}

不确定代码是否有效,我目前无法测试代码。但你可能会明白。

于 2013-05-22T09:32:45.703 回答
0

在写入 while 循环之前,您可以轻松地检查文本。

 if(check your string)
   printer.write(s);
于 2013-05-22T09:33:05.317 回答