Java教程

Java在字符串中查找重复的字符

在此程序中,我们需要查找字符串中的重复字符。
责任重大
要从字符串中查找重复的字符,我们计算字符串中每个字符的出现次数。如果count大于1,则表示字符在字符串中具有重复的条目。在上面的示例中,以绿色突出显示的字符是重复字符。

算法

步骤1: 开始 步骤2: 定义字符串string1 ="Great responsibility" 步骤3: 定义 count 步骤4: 将string1转换为char[]字符。 步骤5: 打印"Duplicate characters in a given string: " 步骤6: SET i =0。直到i重复STEP 7至STEP 11 STEP 7: SET count = 1 步骤8: SET j = i + 1。直到j将步骤8重复到步骤10 步骤9: IF(string[i] == string[j] && string[i]!='')
则then
count = count + 1
string[j] = 0
步骤10: j = j + 1 步骤11: i = i + 1 步骤12: IF(count> 1 && string[i]!= 0),然后打印字符串[i] 步骤13: END

程序:

public class DuplicateCharacters {
    public static void main(String[] args) {
        String string1 = "Great responsibility";
        int count;
        //Converts given string into character array
        char string[] = string1.toCharArray();
        System.out.println("Duplicate characters in a given string: ");
        //Counts each character present in the string
        for(int i = 0; i <string.length; i++) {
            count = 1;
            for(int j = i+1; j <string.length; j++) {
                if(string[i] == string[j] && string[i] != ' ') {
                    count++;
                    //Set string[j] to 0 to avoid printing visited character
                    string[j] = '0';
                }
            }
            //A character is considered as duplicate if count is greater than 1
            if(count > 1 && string[i] != '0')
                System.out.println(string[i]);
        }
    }
}
输出:
Duplicate characters in a given string:
r
e
t
s
i
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4