比较基于Java内部单词的文本行

时间:2014-10-06 01:54:54

标签: java string

我需要从用户提示的文件中读取文本行。我的java程序应该读取该文件的第一行,并检查该行的最后一个单词是否出现在第二行的任何位置。不使用重复,数组或类构造我到目前为止已经提出了这个:

    Scanner keyboard = new Scanner(System.in);

    System.out.println("Enter filename: ");

    File userFile = new File(keyboard.nextLine());

    keyboard.close();

    Scanner input = new Scanner(userFile);

    String firstLine = input.nextLine();
    String secondLine = input.nextLine();

在这之后,我尝试了很多String方法,但没有什么能让我得到满意的结果。我知道我需要用if和else语句来完成我的程序,关于第二行是否包含第一行中的最后一个单词。

**无法找到比较子字符串(文本行中的单词)的方法,我实际上并不知道字符的位置或字符是什么。这是因为所有输入都是用户生成的。有没有办法比较子串,同时保留实际的字符,而不是转换为整数?

**更新我是ECSTATIC这就是我解决这个令人沮丧的问题的方法:

扫描仪键盘=新扫描仪(System.in);

    System.out.println("Enter filename: ");

    File userFile = new File(keyboard.nextLine());

    keyboard.close();

    Scanner input = new Scanner(userFile);

    String firstLine = input.nextLine();
    String secondLine = input.nextLine();

    int lastWordIndex;

    lastWordIndex = ((firstLine.lastIndexOf(" ")) + 1);

    String lastWord = firstLine.substring(lastWordIndex);

    if (secondLine.contains(lastWord))
        System.out.println("It is true the word " + lastWord
                + " appears in the text: " + secondLine);
    else
        System.out.println("The word: " + lastWord
                + " does not appear in the text: " + secondLine);

2 个答案:

答案 0 :(得分:0)

有几种方法可以执行此操作,但您需要获取firstLine字符串中的最后一个单词,然后将其与secondLine字符串进行比较。

您可以在线路上使用substring()方法,然后将lastIndexOf()方法与参数"一起使用。 " (即空白)。如果你向它添加一个,你将得到你的字符串中最后一个单词的第一个字母的索引。

答案 1 :(得分:0)

我就是这样做的:

String lastWord = firstLine.replaceAll(".*\\s+", "");
boolean secondLineHasLastWord = secondLine.contains(lastWord);

或者,为了内联它:

if (secondLine.contains(firstLine.replaceAll(".*\\s+", ""))) {
    // yes
} else {
    // no
}

使用正则表达式来提取最后一个单词,该正则表达式匹配所有内容,包括最后一个空白字符,并将匹配替换为空(有效删除它)。