簡體   English   中英

Java-分隔符會忽略句子結尾處的標點符號

[英]Java - Delimiters ignore punctuation mark at the end of the sentence

因此,我在一個較早的Java線程中問,檢查字符串是否是回文。 對於閱讀回文字符串不區分大小寫

我收到了很多很好的反饋,並且做了很多功課(學到了很多東西!),但是由於這是一個實驗室作業(學院),所以我無法使用建議的方法(字符串生成器)。 下面的代碼(至少是大綱)是我“應該”為該分配編寫代碼的方式,因此這不是方法的問題。

import java.util.*;

public class Lab04 {

public static void main(String[] args) {
    // declaring variables
    String sentence;
    String word;

    // initiating the scanner
    Scanner keyboard = new Scanner(System.in);

    // prompting the user for a sentence

    System.out.println("Please enter the sentence: ");
    sentence = keyboard.nextLine();
    System.out.println("Your input was: " + '"' + sentence + '"');

    // checking if it is a palindrome
    sentence = sentence.toLowerCase();
    Scanner stringScan = new Scanner(sentence);
    **stringScan.useDelimiter("[ \t\n,.-:;'?!\"] + ");**
    char leftChar, rightChar;
    boolean isPalindrome = true;

    while ( stringScan.hasNext() ) {
        word = stringScan.next();
        leftChar = word.charAt(0);
        rightChar = word.charAt(word.length() - 1);
        if (!(leftChar == rightChar))
            isPalindrome = false;   
    }

    if (isPalindrome)
        System.out.println("This is a palindrome.");
    else 
        System.out.println("This is not a palindrome.");


    // checking if it is an alliteration
    sentence = sentence.toLowerCase();
    Scanner stringScan1 = new Scanner(sentence);

    **stringScan1.useDelimiter("[ \t\n,.-:;'?!\"]+");**

    char firstChar = sentence.charAt(0);
    boolean isAlliteration = true;
    while ( stringScan1.hasNext() ) {
        word = stringScan1.next();
        if (firstChar != word.charAt(0) && word.length() > 3)
            isAlliteration = false;
    }

    if (isAlliteration)
        System.out.println("This is an alliteration.");
    else 
        System.out.println("This is not an alliteration.");
}
}

我很好奇的部分用粗體寫。 我一直在搜尋並嘗試使用Java文檔,但是我很難找出分隔符的格式是如何工作的。

當前的分隔符可能很雜亂,包含不必要的字符。

我的目標是使分隔符最后忽略標點符號。 它已經可以接近完美了,但是我需要找到一種方法來忽略最后的標點符號。

例:

輸入:

Doc, note, I dissent. A fast never prevents a fatness. I diet on cod

輸出:

Your input was: "Doc, note, I dissent. A fast never prevents a fatness. I diet on cod"
This is a palindrome.

輸入:

Doc, note, I dissent. A fast never prevents a fatness. I diet on cod.

輸出:

Your input was: "Doc, note, I dissent. A fast never prevents a fatness. I diet on cod"
This is not a palindrome.

關於其余代碼:

我一直在嘗試幾種不同的方法,所以有一些“額外”代碼,例如,我不再需要使用句子.toLowerCase,並且可能只使用一個掃描儀(?),但是我只是想看看是否有針對此問題的修復程序標點問題,因為我覺得剩下的只是我能夠弄清楚自己的細節。

提前致謝!

不知道您的代碼總體上是否做得正確,但是如果您懷疑要從輸入字符串中刪除標點符號,那將非常簡單。

String lowerCaseInput = input.toLowerCase();
String strippedInput = lowerCaseInput.replaceAll("[^a-z]", "");

轉換為小寫字母后,replaceAll()會刪除所有非小寫字母。

感謝Patashu的更正。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM