in reply to How to remove duplicate characters in a string in place
G'day punitpawar,
"Is there a way by making use of s/// ..."
You're starting with a solution and then trying to make it fit a problem. This is back-to-front: start with a problem and then find an appropriate solution.
The output of your second example (cdghijkmnoestsr) contains an 'e' which shouldn't be there: the original string (abcdeffghijkllmnoppqestqaserb) contains three 'e's.
As others have already noted, s/// does not seem appropriate. Here's how I might have tackled this problem:
#!/usr/bin/env perl -l use strict; use warnings; my @test_strings = qw{ abcdefghiaabccdjklm abcdeffghijkllmnoppqestqaserb }; remove_duplicate_chars($_) for @test_strings; sub remove_duplicate_chars { my $str = shift; my %seen; my @chars = grep { ! $seen{$_}++ } split //, $str; my $uniq = join '', grep { $seen{$_} == 1 } @chars; print "IN: $str"; print "OUT: $uniq"; return; }
Output:
IN: abcdefghiaabccdjklm OUT: efghijklm IN: abcdeffghijkllmnoppqestqaserb OUT: cdghijkmnotr
— Ken
|
|---|