Java程序查找字符串中所有重复字符


字符串中重复的字符是指出现不止一次的字符。在Java中,String是一个非基本数据类型,包含一个或多个字符,并用双引号(" ")括起来。

根据题意,给定一个字符串,我们的任务是编写一个Java程序来查找该字符串中的所有重复字符。我们可以使用for循环和嵌套for循环来解决这个问题。


示例场景

Input: String str = "Apple";
Output: duplicate_char = p; 

p是一个重复字符,因为它出现不止一次。

使用for循环

在这种方法中,我们遵循以下步骤:

  • 首先将给定的字符串转换为字符数组,然后使用Arrays.sort()方法对其进行排序。
  • 接下来,使用for循环迭代字符数组的元素。
  • 使用if块检查当前字符是否等于下一个字符。
  • 如果相等,则将该字符标记为重复字符,并重复此过程,直到数组长度结束。

示例

在这个Java程序中,我们使用for循环来查找并打印字符串中的重复字符。

import java.util.Arrays;
public class Example {
   public static void checkDupliChar(String str) {
      System.out.println("The string is: " + str);
      char[] carray = str.toCharArray();
      // sorting the character array
      Arrays.sort(carray);
      System.out.println("Duplicate Characters in the above string are: ");
      // for loop to print duplicate character
      for (int i = 0; i < carray.length - 1; i++) {
         if (carray[i] == carray[i + 1]) {
            System.out.println(carray[i]);
            // loop to skip next occurrence of same character
            while (i < carray.length - 1 && carray[i] == carray[i + 1]) {
               i++;
            }
         }
      }
   }
   // main method
   public static void main(String[] args) {
      checkDupliChar("tutorialspoint");
   }
}

以上代码的输出如下:

The string is: tutorialspoint
Duplicate Characters in the above string are: 
i
o
t

使用嵌套for循环

按照以下步骤,使用嵌套for循环方法查找字符串中所有重复字符:

  • 将给定的字符串转换为字符数组。
  • 索引0运行外部for循环到字符数组的长度。
  • 内部for循环将从current+1索引运行到字符数组的长度。
  • 接下来,我们使用if块检查当前字符是否等于下一个字符。
  • 如果相等,则打印重复字符。

示例

以下示例演示如何使用嵌套for循环查找字符串中所有重复字符。

public class Example {
   public static void main(String argu[]) {
      String str = "beautiful sea";
      char[] carray = str.toCharArray();
      System.out.println("The string is: " + str);
      System.out.print("Duplicate Characters in above string are: ");
	  // nested for loop to print duplicate characters
      for (int i = 0; i < str.length(); i++) {
         for (int j = i + 1; j < str.length(); j++) {
            if (carray[i] == carray[j]) {
               System.out.print(carray[j] + " ");
               break;
            }
         }
      }
   }
}

以上代码的输出为:

The string is: beautiful sea
Duplicate Characters in above string are: e a u 

更新于:2024年8月1日

51K+ 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.