如何在不使用replace()方法的情况下从字符串中移除子字符串?

huangapple go评论62阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年10月2日 12:59:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/64166361.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定