[英]How would I replace a substring in Java without using the replace method?
What I need to do is replace the letter the user wants to replace in a string with X. Here's an example:我需要做的是用 X 替换用户想要在字符串中替换的字母。 这是一个例子:
replaceLetterWithX("asdfgsdfghfghj","s") replaceLetterWithX("asdfgsdfghfghj","s")
aXdfgXdfghfghj aXdfgXdfghfghj
But I can't use the replace method.但是我不能使用替换方法。 I also need to use the substring, length, and equals methods.
我还需要使用 substring、length 和 equals 方法。 I'm a bit confused about where to start.
我对从哪里开始有点困惑。 Here's what my code looks like now:
这是我的代码现在的样子:
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;
}
This can be done with a simple for loop using the charAt method.这可以通过使用 charAt 方法的简单 for 循环来完成。 By looping through the strings and comparing each character with the character to be replaced, we can construct the replaced string from scratch.
通过遍历字符串并将每个字符与要替换的字符进行比较,我们可以从头开始构造替换字符串。 Keep in mind that this is case-sensitive, I suggest you do some research into the Java documentation to learn more about how to do that.
请记住,这是区分大小写的,我建议您对 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.