function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SambitNayakSambitNayak 

Find duplicate in a string

Hi All,

I was asked this Q in one of the interviews. Eliminate all duplicate values from a string. For Eg. I/P = 'THEMISSISSIPPI'
O/P = 'THEM' (all other values are truncated because they are duplicates)
Can you please help. Appreciate your response.

Thanks.
Best Answer chosen by SambitNayak
Surya GSurya G
HI SambitNayak,

It works with below code. But, I am not sure, if there is any direct method to achieve this.
Try this is in dev console.
String demoString = 'THEMISSISSIPPI';
List<String> charList = demoString.split('');
List<String> stringList = new List<String>();
for(String s : charList) {
    if(!(demoString.countMatches(s) > 1)) {
        stringList.add(s);
    } 
}
String finalString = String.join(stringList,'');
system.debug(finalString); // "THEM"

Thanks
Surya G

All Answers

Surya GSurya G
HI SambitNayak,

It works with below code. But, I am not sure, if there is any direct method to achieve this.
Try this is in dev console.
String demoString = 'THEMISSISSIPPI';
List<String> charList = demoString.split('');
List<String> stringList = new List<String>();
for(String s : charList) {
    if(!(demoString.countMatches(s) > 1)) {
        stringList.add(s);
    } 
}
String finalString = String.join(stringList,'');
system.debug(finalString); // "THEM"

Thanks
Surya G
This was selected as the best answer
Lukesh KarmoreLukesh Karmore
 Nice, Surya👏
SambitNayakSambitNayak
Thanks Surya. That shows your great dexterity and command over Apex.