gpt4 book ai didi

Java:如何用单个字符替换连续字符?

转载 作者:行者123 更新时间:2023-12-01 16:42:20 25 4
gpt4 key购买 nike

如何在java中用单个字符替换连续字符?

String fileContent = "def  mnop.UVW";
String oldDelimiters = " .";
String newDelimiter = "!";
for (int i = 0; i < oldDelimiters.length(); i++){
Character character = oldDelimiters.charAt(i);
fileContent = fileContent.replace(String.valueOf(character), newDelimiter);
}

当前输出:def!!mnop!UVW

所需输出:def!mnop!UVW

请注意,两个空格被替换为两个感叹号。如何用一个分隔符替换连续的分隔符?

最佳答案

由于您想要匹配旧分隔符中的连续字符,因此正则表达式解决方案在这里似乎不可行。如果它属于旧的分隔符之一,您可以改为逐字符匹配,然后将其设置为新的分隔符,如下所示。

import java.util.*;
public class Main{
public static void main(String[] args) {
String fileContent = "def mnop.UVW";
String oldDelimiters = " .";

// add all old delimiters in a set for fast checks
Set<Character> set = new HashSet<>();
for(int i=0;i<oldDelimiters.length();++i) set.add(oldDelimiters.charAt(i));

/*
match all consecutive chars at once, check if it belongs to an old delimiter
and replace it with the new one
*/

String newDelimiter = "!";
StringBuilder res = new StringBuilder("");
for(int i=0;i<fileContent.length();++i){
if(set.contains(fileContent.charAt(i))){
while(i + 1 < fileContent.length() && fileContent.charAt(i) == fileContent.charAt(i+1)) i++;
res.append(newDelimiter);
}else{
res.append(fileContent.charAt(i));
}
}

System.out.println(res.toString());
}
}

演示: https://onlinegdb.com/r1BC6qKP8

关于Java:如何用单个字符替换连续字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61073258/

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