public class StringTest{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String str1 = scanner.nextLine(); // 使用nextLine()来获取整行输入
char[] chars = str1.toCharArray(); // 将字符串转换为字符数组
boolean[] isTrue = new boolean[chars.length]; // 初始化标记数组
int i = 0; // 初始化索引
long began = System.currentTimeMillis();
while (i < chars.length) {
if (isTrue[i]) {
i++; // 如果当前字符已经被处理过,直接跳到下一个字符
continue;
}
int count = 1; // 当前字符至少出现一次
int j = i + 1; // 从当前字符的下一个位置开始查找
// 查找当前字符在字符串中的所有出现
while (j < chars.length) {
if (chars[j] == chars[i]) {
count++;
isTrue[j] = true; // 标记这个字符已经被计数
}
j++;
}
System.out.println(chars[i] + "出现的次数为" + count);
i++; // 更新索引,准备下一次迭代
}
long end = System.currentTimeMillis();
System.out.println("程序执行时间: " + (end - began) + "毫秒");
scanner.close();
}
}
java关于使用while循环加for来寻找字符串中的相同字母的出现次数
最新推荐文章于 2024-05-09 23:10:04 发布