Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: How to remove duplicate characters in a string in place

by kcott (Archbishop)
on Feb 22, 2016 at 06:43 UTC ( [id://1155791]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1155791]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (10)
As of 2024-04-18 09:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found