package com.tp.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class DuplicateString {
public static void main(String[] args) throws IOException {
String res = "";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("============Input=============");
String str = br.readLine();
while (str.length() > 0) {
int c = 0;
for (int j = 0; j < str.length(); j++) {
if (str.charAt(0) == str.charAt(j))
c = c + 1;
}
res = "The" + res + str.charAt(0) + " repeated for " + c + " times " + "n";
String k[] = str.split(str.charAt(0) + "");
str = new String("");
for (int i = 0; i < k.length; i++)
str = str + k[i];
}
System.out.print(res);
}
}
输入:
sfkljsdkjds
TheTheTheTheTheThes repeated for 3 times
f repeated for 1 times
k repeated for 2 times
l repeated for 1 times
j repeated for 2 times
d repeated for 2 times
每次都在字符串中追加res
,并且在the
之后没有空格。尝试使用StringBuilder
构建您需要的最后一个字符串
例如:
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("============Input=============");
String str = br.readLine();
StringBuilder sb = new StringBuilder();
while (str.length() > 0) {
int c = 0;
for (int j = 0; j < str.length(); j++) {
if (str.charAt(0) == str.charAt(j))
c += 1;
}
sb.append(String.format("The %s repeated for %d timesn", str.charAt(0), c));
str = str.replace(str.subSequence(0, 1), "");
}
System.out.print(sb.toString());
}
Yo可以看到,我们创建了一个StringBuilder类,并不断地添加到它。使用String.Format
,我们也可以以可读的方式构建字符串。然后我们打印最终结果。
============Input=============
sfkljsdkjds
The s repeated for 3 times
The f repeated for 1 times
The k repeated for 2 times
The l repeated for 1 times
The j repeated for 2 times
The d repeated for 2 times
此外,由于我们每次都会获取字符串的第一个字母,因此我们还可以用一个空值来替换这些出现的字符,如上所示,这简化了循环。