每个newLine的字符验证

时间:2015-01-19 02:12:30

标签: java

我试图找到一种方法来验证每行是否从" srcFile"以字母字符开头。我尝试使用Character.isLetter()方法,但它抱怨行声明为String而不是char数组......从我的想法来看,String是一个字符数组,但显然isLetter()不起作用那样。我想知道我可以用什么方法。我想过滤srcFile中的数据并将其放置为HashMap和Vector,但我首先需要找到一种有效且干净的方法来确定该行是否以字母字符开头。我还想过使用String.contains(),因为我知道我正在寻找什么特定的char序列,但它会更加冗长,可能是不必要的编码方式,这也使我的程序不那么通用,我想要在一定程度上。

    try {
        Scanner myScanner = new Scanner(srcFile);
        // Why not declare line outside while loop 
        // and write cond. as (line = myScan... != null) ?
        while (myScanner.hasNextLine()) {
            String line = myScanner.nextLine();
            //System.out.println(line);

            if (Character.IsLetter(line[0])) {

            }
        }
        myScanner.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

剩下的条件是这样的:

                //if first char start with a aplha char, move to the ticket list
                if (Char.IsLetter(line[0]))
                {
                    ticket t = new ticket();
                    t.parseLine(line);
                    //logger.Debug(line);

                    tickets.Add(t);
                }
                else
                {
                    sbPeople sbuPeople = new sbPeople();
                    sbuPeople.parseLine(line);

2 个答案:

答案 0 :(得分:0)

要获取字符串中的第一个字符,请使用line.charAt(0)。只有数组使用[]编制索引,而字符串不是数组。

答案 1 :(得分:0)

您还可以使用正则表达式。例如:

String line = myScanner.nextLine();
if (line.matches("^\\p{Alpha}.*$")) {
    System.out.printf("Starts with an alphabetic character: %s%n", line);
    ...
} else {
    ...
}

正则表达式中每个项目的说明:

NODE                     EXPLANATION
---------------------------------------------------------------------
  ^                        the beginning of the string
---------------------------------------------------------------------
  \p{Alpha}                any character of: letters
---------------------------------------------------------------------
  .*                       any character except \n (0 or more times
                           (matching the most amount possible))
---------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string