It is necessary to go through all the characters of a string, and if it is absent in the resulting string, add it to it. Here's what I got:

String wordsChangeNotRepeat = ""; for (char c : wordsChange.toCharArray()) { if (!wordsChangeNotRepeat.contains(c)) //тут подчёркивает с wordsChangeNotRepeat += c; } System.out.println(wordsChangeNotRepeat); 

    2 answers 2

    Change

     if (!wordsChangeNotRepeat.contains(c)) 

    on

     if (wordsChangeNotRepit.indexOf(c) == -1) 

    Instead of checking wordsChangeNotRepeat every time, wordsChangeNotRepeat can use HashSet :

     StringBuilder sb = new StringBuilder(); Set<Character> set = new HashSet<>(); for (char c : str.toCharArray()) { if (!set.contains(c)) { sb.append(c); set.add(c); } } String result = sb.toString(); 

    On small lines the difference will not be noticeable, however, for example, on a line of 10 million characters, the range of charcode-s of which is 1074, the difference is noticeable:

     indexOf: 1180ms HashSet: 77ms 

    Since the resulting string is quite short, there are no advantages from using StringBuilder instead of resultString += c in terms of execution time, but in general it is recommended to use StringBuilder for such purposes.