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.");
}
最佳答案
内置检查该角色是否存在。
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++;
}
}
不确定代码是否有效,我目前无法测试代码。但你可能会明白这个想法。
关于java - 如何确定字符串是否以特定字符开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16688256/