繁体   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