英文:
How to remove a substring from a string without using replace() method?
问题
String string = "yesnoyesnoyesnoyesno";
String substring = "no";
如何将字符串中的每个子字符串删除,以使得最终结果为 "yesyesyesyes"?
英文:
String string = "yesnoyesnoyesnoyesno";
String substring = "no";
How do I remove every occurrence of the substring from the string so it ends up being "yesyesyesyes"?
答案1
得分: 4
如果您使用的是Java 8或更高版本,则可以尝试在"no"
上拆分输入,然后将生成的数组组合成一个字符串:
String string = "yesnoyesnoyesnoyesno";
string = String.join("", string.split("no"));
System.out.println(string);
这将打印:
yesyesyesyes
英文:
If you are using Java 8+, then you could try splitting the input on "no"
and then joining the resulting array together into a string:
String string = "yesnoyesnoyesnoyesno";
string = String.join("", string.split("no"));
System.out.println(string);
This prints:
yesyesyesyes
答案2
得分: 0
这并未使用replace()
,所以从技术上讲它满足要求:
String str = string.replaceAll("no", "");
英文:
This doesn't use the replace()
, so technically it meets the brief:
String str = string.replaceAll("no", "");
答案3
得分: 0
String input = "yesnoyesnoyesno";
String output = "";
for (String token : input.split("no"))
output = output.concat(token);
System.out.println(output);
英文:
String input = "yesnoyesnoyesno";
String output="";
for(String token : input.split("no") )
output = output.concat(token);
System.out.println(output);
It prints:
yesyesyesyes
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论