簡體   English   中英

如何在不使用 replace 方法的情況下替換 Java 中的子字符串?

[英]How would I replace a substring in Java without using the replace method?

我需要做的是用 X 替換用戶想要在字符串中替換的字母。 這是一個例子:

replaceLetterWithX("asdfgsdfghfghj","s")

aXdfgXdfghfghj

但是我不能使用替換方法。 我還需要使用 substring、length 和 equals 方法。 我對從哪里開始有點困惑。 這是我的代碼現在的樣子:

public static String replaceLetterWithX(String str, String c)
    {
        //This method will return 'str' with all instances of letter 'c' replaced
        //by 'X'

        String result="";
        
        int count = 0;

        //Code here

        return result;
    }

這可以通過使用 charAt 方法的簡單 for 循環來完成。 通過遍歷字符串並將每個字符與要替換的字符進行比較,我們可以從頭開始構造替換字符串。 請記住,這是區分大小寫的,我建議您對 Java 文檔進行一些研究,以了解有關如何執行此操作的更多信息。

public static String replaceLetterWithX(String str, String c)
    {
        //This method will return 'str' with all instances of letter 'c' replaced
        //by 'X'

        String result="";

        //Code here
        //looping through each character in the string 
        for (int i = 0; i < str.length(); i++)
        {
            //converting the character at i to string and comparing it with the given letter
            if (Character.toString(str.charAt(i)).equals(c))
            {
                result += "X";
            }
            //if it isn't add the original letter in the string
            else
            {
                result += str.charAt(i);
            }
        }
        return result;
    }

暫無
暫無

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

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