java - 如何在不使用 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;
}
解决方案
这可以通过使用 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;
}
推荐阅读
- java - 没有密码而是证书的用户身份验证?
- java - 按 /1;2;3;4;5 顺序读取参数列表
- angular - forkJoin 的问题,代码不会在订阅后运行
- symfony - JMS Serializer:如何在不到处添加注释的情况下传播属性的组排除?
- php - 应用过滤器时,帖子类型订单不起作用
- javascript - 如何从实时数据库中的所有 randomId 中获取特定键值,使用 javaScript 的 Firebase 函数
- sql - Oracle 查询以获取初始更改值
- javascript - Angular6 HttpClient:在获取请求时注入标头在 Chrome 和 IE11 上不起作用
- javascript - 正则表达式在 javascript 和 .NET 中给出不同的结果
- python - 提取括号python之间的年份