Home > Back-end >  java - how to find duplicate characters in a string and concat them to a new string
java - how to find duplicate characters in a string and concat them to a new string

Time:07-10

  • I take in a string aabullc

  • returingStrin should be assigned aall after the loop since a and l are duplicates

  • strings with more then 1 dupe like example: (3x a). aaabullc will never be passed in

    public static String rearrangeLetters(String S)
    {
    
    String returnString;
    
     for(int i = 0; i<S.length()-1; i  ){
         for(int j = i 1; i<S.length()-1-i; j  ){
             if(S.charAt(i) == (S.charAt(j))){
             String char1 = String.valueOf(S.charAt(i));
             returnString = returnString.concat(char1);
             }
          }
      }
    
      System.out.println(returnString);
    
        return returnString;
    }
    

Code briefing:

  • nested for loop starts at first letter in string and compares to the second letter until it reachs the end.
  • the inner loop length gets sorter depending on the outer loops.
  • if character matches we add it to returningString

Issue: does not like String char

CodePudding user response:

char is a reserved keyword in JAVA. So it cannot be used as a variable name.

  • Related