我想按字母顺序排列重复的字符,我能做什么?

kokeuurv  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(245)
import java.util.Scanner;
public class Chupapi {

static Scanner input = new Scanner(System.in);

public static void main(String[] args) {

    String str = "";
    System.out.print("Enter string: ");
    str = input.nextLine();

    getConsonantCount(str);
}

public static void getConsonantCount(String str) {
    char string[] = str.toCharArray();

    System.out.print("Duplicate characters in a given string: ");
    for(int i = 0, count = 0; i <string.length; i++) {
        count = 1;
        for(int j = i+1; j <string.length; j++) {
            if(string[i] == string[j] && string[i] != ' ') {
                count++;
                string[j] = '0';
            }
        }
        if(count > 1 && string[i] != '0')
            System.out.print(string[i]);
    }
  }
}

我想对“给定字符串中的重复字符”进行分类:“按字母顺序的输出示例是,

"Duplicate characters in a given string: heuro"
 I want it to be
"Duplicate characters in a given string: ehoru"

这就是我想用这段代码做的所有事情,关于我应该做什么或使用什么的提示?

g0czyy6m

g0czyy6m1#

在查找重复字符之前,请使用arrays.sort()对数组进行排序。

public static void getConsonantCount(String str)
{
    char string[] = str.toCharArray();

    Arrays.sort(string);

    System.out.print("Duplicate characters in a given string: ");
    for (int i = 0, count = 0; i < string.length; i++)
    {
        count = 1;
        for (int j = i + 1; j < string.length; j++)
        {
            if (string[i] == string[j] && string[i] != ' ')
            {
                count++;
                string[j] = '0';
            }
        }
        if (count > 1 && string[i] != '0')
            System.out.print(string[i]);
    }
}

相关问题