首页 > 解决方案 > 如何在不使用 replace 方法的情况下替换 Java 中的子字符串?

问题描述

我需要做的是用 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;
    }

标签: java

解决方案


这可以通过使用 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;
    }

推荐阅读