gpt4 book ai didi

java - 如何替换字符串中除某些字符之外的所有字符?

转载 作者:行者123 更新时间:2023-12-02 01:47:47 24 4
gpt4 key购买 nike

public class HelloWorld {
public static void main(String []args) {
//replace all char to 1 other then c and g
String str = "abcdefghijklmnopqrstuvwxyz";
if (str == null || str.length() == 0) {
return;
}
String answer = str.replaceAll("[^cg]+", "1");
System.out.println(answer);
}
}
  • 当前输出:1c1g1
  • 想要的输出:11c111g111111111111111111

最佳答案

Now here I am getting an output as 1c1g1, but what I want is 11c111g111111111111111111

删除+。这表示“匹配前面的一个或多个”,但您要将这一系列匹配字符替换为一个 1

所以:

public class HelloWorld {

public static void main(String []args){
//replace all char to 1 other then c and g
String str = "abcdefghijklmnopqrstuvwxyz";
if (str == null || str.length() == 0) {
return;
}
String answer = str.replaceAll("[^cg]", "1");
// No + here ------------------------^
System.out.println(answer);
}
}

Live Copy

关于java - 如何替换字符串中除某些字符之外的所有字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53501824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com