Search code examples
javaconcatenationnested-loops

How to find duplicate characters in a string and concat them to a new string


  • 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


Solution

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