java - 如何确定字符串是否以特定字符开头?

标签 java

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/

相关文章:

java - Web框架性能比较

c# - 特殊类型查询的数据结构

java - 快速包含和后进先出数据结构

java - 对象可以有访问修饰符吗?

java - "<indentifier> expected"是什么意思?

java - 在线程之间共享一个变量?

java - Edittext.setmaxLines(3) 以编程方式不起作用

Java 使用比较器

java - 相同的类(class)类型转换?

java - ImageView 的 onTouch 移动?