用JAVA设计一个方法返回一个新字符串,要求求新字符串删除原字符串中连续且重复的字符,重复字符只保留一个
时间: 2024-03-09 08:47:17 浏览: 20
可以使用StringBuilder来实现该方法,具体实现如下:
```java
public static String removeDuplicateChars(String str) {
StringBuilder builder = new StringBuilder();
if (str == null || str.isEmpty()) {
return str;
}
char lastChar = str.charAt(0);
builder.append(lastChar);
for (int i = 1; i < str.length(); i++) {
char currentChar = str.charAt(i);
if (currentChar != lastChar) {
builder.append(currentChar);
lastChar = currentChar;
}
}
return builder.toString();
}
```
该方法首先判断输入的字符串是否为空或者长度为0,如果是则直接返回原字符串。接着使用StringBuilder来保存新的字符串,遍历原字符串,如果当前字符和上一个字符不相同,则将当前字符添加到StringBuilder中,并将当前字符设为lastChar。最后将StringBuilder转换为String并返回即可。