簡體   English   中英

忽略大寫/小寫字符串

[英]Ignoring upper/lowercase strings

我的目標是將句子中的“ java”一詞的任何形式更改為“ JAVA”。我已經完成了所有工作,但在混合情況下,我的代碼無法讀取,例如:JaVa,JAva等。 我知道我應該使用toUpperCase和toLowerCase或equalsIgnoreCase,但是我不確定如何正確使用它。 我不允許使用全部替換或替換,老師要使用子字符串方法。

    Scanner input=new Scanner(System.in);
    System.out.println("Enter a sentence with words including java");
    String sentence=input.nextLine();

    String find="java";
    String replace="JAVA";
    String result="";
    int n;
    do{
        n=sentence.indexOf(find);
        if(n!=-1){
            result =sentence.substring(0,n);
            result=result +replace;
            result = result + sentence.substring(n+find.length());
            sentence=result;            
        }
    }while(n!=-1);
    System.out.println(sentence);
}

}

您不能使用String.indexOf做到這一點,因為它區分大小寫。

一種簡單的解決方案是使用不區分大小寫模式的正則表達式。 例如

Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(str).replaceAll(repl);

這樣做還有一個好處,就是避免了您當前用於進行替換的混亂字符串重擊。


在您的示例中,您的輸入字符串也可用作正則表達式...,因為它不包含任何正則表達式元字符。 如果是這樣,那么簡單的解決方法是使用Pattern.quote(str) ,它將把元字符視為文字匹配。

String.replaceAll(...)是用於對字符串進行正則表達式替換的“便捷方法”,這也不值錢,盡管您不能在示例中使用它,因為它會區分大小寫。


作為記錄,這里有一個部分解決方案,它通過字符串重擊來完成這項工作。 @ben-此內容供您閱讀和理解...請勿復制。 故意鼓勵您仔細閱讀它。

// WARNING ... UNTESTED CODE
String input = ...
String target = ...
String replacement = ...
String inputLc = input.lowerCase();
String targetLc = target.lowerCase();
int pos = 0;
int pos2;
while ((pos2 = inputLc.indexOf(targetLc, pos)) != -1) {
    if (pos2 - pos > 0) {
        result += input.substring(pos, pos2);
    }
    result += replacement;
    pos = pos2 + target.length();
}
if (pos < input.length()) {
    result += input.substring(pos);
}

result使用StringBuilder而不是String可能更有效。

一個快速的解決方案是完全刪除do/while循環,而僅對String.replaceAll()使用不區分大小寫的正則表達式,例如:

sentence = sentence.replaceAll("(?i)java", "JAVA");
System.out.println(sentence);

或者,根據您的變量命名更一般:

sentence = sentence.replaceAll("(?i)" + find, replace);
System.out.println(sentence);

樣例程序

編輯:

根據您的評論,如果您需要使用substring方法,這是一種方法。

首先,由於String.indexOf區分大小寫的比較,因此您可以編寫自己的不區分大小寫的方法,因此將其稱為indexOfIgnoreCase() 這種方法看起來像:

// Find the index of the first occurrence of the String find within the String str, starting from start index
// Return -1 if no match is found
int indexOfIgnoreCase(String str, String find, int start) {
    for(int i = start; i < str.length(); i++) {
        if(str.substring(i, i + find.length()).equalsIgnoreCase(find)) {
            return i;
        }
    }
    return -1;
}

然后,您可以按以下方式使用此方法。

您找到所需單詞的索引,然后將字符串中該單詞之前的部分(直到找到的索引)添加到結果中,然后添加找到的單詞的替換版本,然后添加其余部分找到的單詞后的字符串。

最后,您通過找到的單詞的長度來更新起始搜索索引。

String find = "java";
String replace = "JAVA";
int index = 0;
while(index + find.length() <= sentence.length()) {
    index = indexOfIgnoreCase(sentence, find, index);       // use the custom indexOf method here
    if(index == -1) {
        break;
    }
    sentence = sentence.substring(0, index) +               // copy the string up to the found word
               replace +                                    // replace the found word
               sentence.substring(index + find.length());   // copy the remaining part of the string
    index += find.length();
}
System.out.println(sentence);

Sample Program

您可以使用StringBuilder來提高效率,因為+運算符會在每個串聯中創建一個新的String。 在這里閱讀更多

此外,您可以在單個方法中結合indexOfIgnoreCase的邏輯和其余代碼,例如:

String find = "java";
String replace = "JAVA";
StringBuilder sb = new StringBuilder();
int i = 0;
while(i + find.length() <= sentence.length()) {
    // if found a match, add the replacement and update the index accordingly
    if(sentence.substring(i, i + find.length()).equalsIgnoreCase(find)) {
        sb.append(replace);
        i += find.length();
    } 
    // otherwise add the current character and update the index accordingly
    else {
        sb.append(sentence.charAt(i));
        i++;
    }
}
sb.append(sentence.substring(i)); // append the rest of the string
sentence = sb.toString();
System.out.println(sentence);

您被允許使用toUpperCase()嗎? 試試這個

 Scanner input=new Scanner(System.in);
    System.out.println("Enter a sentence with words including java");
    String sentence=input.nextLine();

    String find="java";
    String replace="JAVA";
    String result="";

    result = sentence.toLowerCase();
    result = result.replace(find,replace);
    System.out.println(result);
}

回復結果:))

更新:基於

我已經完成了所有工作,但是我的代碼在混合情況下無法讀取,例如:JaVa,JAva等。

你可以使用你的代碼

   Scanner input=new Scanner(System.in);
    System.out.println("Enter a sentence with words including java");
    String sentence=input.nextLine();

    String find="java";
    String replace="JAVA";
    String result="";
    int n;
    do{
        //for you to ignore(converts the sentence to lowercase) either lower or upper case in your sentence then do the nxt process
        sentence = sentence.toLowerCase();

        n=sentence.indexOf(find);
        if(n!=-1){
            result =sentence.substring(0,n);
            result=result +replace;
            result = result + sentence.substring(n+find.length());
            sentence=result;            
        }
    }while(n!=-1);
    System.out.println(sentence);
}

更新2:我把toLowerCase轉換放在循環之外。

public static void main(String[] args){

            String sentence = "Hello my name is JAva im a jaVa Man with a jAvA java Ice cream";
            String find="java";
            String replace="JAVA";
            String result="";
            int n;
            //for you to ignore(converts the sentence to lowercase) either lower or upper case in your sentence then do the nxt process
            sentence = sentence.toLowerCase();
            System.out.println(sentence);

            do{


                n=sentence.indexOf(find);
                if(n!=-1){
                    result =sentence.substring(0,n);
                    result=result +replace;
                    result = result + sentence.substring(n+find.length());
                    sentence=result;            
                }
            }while(n!=-1);

            System.out.println(sentence);
    }

結果

你好,我的名字是java,我是一個帶有java java冰淇淋的java人

你好,我叫JAVA,是一個JAVA男子,一個JAVA JAVA冰淇淋

暫無
暫無

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

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