用Java写一个把单词中相同字母变为一个的代码
时间: 2024-05-15 15:19:25 浏览: 7
以下是一个Java代码示例,可以将单词中相同字母变为一个:
```java
public class RemoveDuplicateCharacters {
public static String removeDuplicates(String word) {
StringBuilder sb = new StringBuilder();
char lastChar = '\0';
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (c != lastChar) {
sb.append(c);
lastChar = c;
}
}
return sb.toString();
}
public static void main(String[] args) {
String word = "hello";
String result = removeDuplicates(word);
System.out.println(result); // "helo"
}
}
```
这个代码使用一个StringBuilder来构建新的字符串,遍历原始字符串并将不同的字符添加到新的字符串中。在遍历过程中,代码跟踪上一个字符并比较当前字符是否与它相同。如果不同,则将当前字符添加到新字符串中,并将其设置为上一个字符。这样就可以确保只有不同的字符被添加到新字符串中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)