java - Removing duplicate characters in a String (user inputted keyword) -


private string removeduplicates(string userkeyword){   int wordlength = userkeyword.length();   int lengthcounter;   (lengthcounter=0; lengthcounter<wordlength; lengthcounter++){     if (userkeyword.charat(lengthcounter) != userkeyword.charat(lengthcounter + 1)){       string revisedkeyword = "" + userkeyword.charat(lengthcounter);       userkeyword = revisedkeyword;      }  }   return userkeyword; } 

im new java, havent used string builders, strung buffer,, arrays, etc yet.... havent gotten loops figured ll easiest way use... please help.

there infinitely many ways this. finding own solution within bounds of toolset you've established learning program about. here 1 possible solution thinking:

create set, default can hold unique values

set<character> myset = new hashset<character>(); 

then loop on characters in string, adding each myset

myset.add(c); 

when you're done, set have list of characters unique , in order, can print them out with

for (char c : myset) {     system.out.println(c) } 

edit:

here simple set using nested loops

string s = "einstein"; //this word duplicates in string temp = ""; //in string, add characters not duplicates boolean isduplicate = false; //this reset every out iteration 

i'm using hard example keep things simple. please understand string temp start empty, when whole process done, goal have temp have same characters einstein without duplicates. stein

public static void main (string[] args) {      string s = "einstein";     string temp = "";     boolean isduplicate = false;      (int = 0; < s.length(); i++) {         isduplicate = false;         char comparisonchar = s.charat(i);         (int j = + 1; j < s.length(); j++) {             char nextchar = s.charat(j);             if (comparisonchar == nextchar) isduplicate = true;         }         if (!isduplicate) temp = temp + comparisonchar;     }      system.out.println(temp); //should print `stein` } 

}

now haven't tested it's has bugs, walk through mentally , try understand it. ask me when confused.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -