下面是我用于查找重复项的 Java 程序。这里重复输出我只想要重复的字符作为输出

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    String s1 = sc.nextLine();

    int count = 0;


    // breaking in to characters

    char[] str1 = s1.toCharArray();

    System.out.println("Duplicate are :");


    //creating outer loop for string length

    for (int i = 0; i < s1.length(); i++) {


        //creating inner loop for comparison

        for (int j = i + 1; j < s1.length(); j++) {


            //comparing value of i and j

            if (str1[i] == str1[j]) {


                System.out.println(str1[j]);

                System.out.println(count);


                //increment after comparison

                count++;

                break;

            }

        }

    }

    sc.close();

}

输出:


        aassdesdd

        Duplicate are :

        a

        s

        s

        d

        d


一只名叫tom的猫
浏览 163回答 2
2回答

凤凰求蛊

如果您只想打印连续的重复项(即对于输入“aassdesdd”,输出 asd 而不是 assdd),您可以将内部循环与等式检查结合起来:for(int i = 0; i < s1.length(); i++) {&nbsp; &nbsp; for(int j = i + 1; j < s1.length() && str1[i] == str1[j]; j++) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(str1[j]);&nbsp; &nbsp; }}

ABOUTYOU

如果您只想打印连续的不同字符,那么您只有一个循环,并且每次迭代,您都可以检查当前和下一个字符。如果它们相同,则打印。为了避免再次打印相同的字符,我们可以设置标志。这可以使用单循环来实现&nbsp; &nbsp; char[] str1 = "aasssdesdd".toCharArray();&nbsp; &nbsp; boolean flag=true;&nbsp; &nbsp; for(int i = 0; i < str1.length-1; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (flag && str1[i]==str1[i+1])&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(str1[i]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // we found duplicate, mark the flag as false&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; flag=false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; flag = true;&nbsp; &nbsp;}输出 :asd
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java