用java编写一个字符串压缩程序。通过键盘输入一串小写字母(a~z)组成的字符串。将字符串中连续出现字母进行压缩,并输出压缩后的字符串。压缩规则:1、仅压缩连续反复出现的字符。比方字符串"abcbc"因为无连续反复字符。压缩后的字符串还是"abcbc"。2、压缩字段的格式为"字符重复的次数+字符"。比如:字符串"xxxyyyyyyz"压缩后就成为"3x6yz"。
时间: 2024-03-11 11:49:21 浏览: 253
好的,以下是用Java编写的字符串压缩程序代码:
```java
import java.util.Scanner;
public class StringCompression {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("请输入字符串:");
String str = scan.nextLine();
StringBuilder sb = new StringBuilder();
int count = 1;
char lastChar = str.charAt(0);
for (int i = 1; i < str.length(); i++) {
char currChar = str.charAt(i);
if (currChar == lastChar) {
count++;
} else {
if (count > 1) {
sb.append(count);
}
sb.append(lastChar);
count = 1;
lastChar = currChar;
}
}
if (count > 1) {
sb.append(count);
}
sb.append(lastChar);
System.out.println("压缩后的字符串为:" + sb.toString());
}
}
```
运行结果如下:
```
请输入字符串:xxxyyyyyyz
压缩后的字符串为:3x6yz
```
该程序使用了StringBuilder来拼接压缩后的字符串,遍历输入的字符串,当当前字符与上一个字符相同时,计数器加1,否则将上一个字符及其计数器加入StringBuilder中,并更新上一个字符和计数器。最后还要检查最后一个字符是否需要加入StringBuilder中。
阅读全文
相关推荐













