in reply to Unique character in a string?

Similar questions have been asked quite a few times. (More bluntly, Try a [id://Super Search|little research] first.).



One way (probably the best) is to use the uniq function from List::MoreUtils. This is used something like this:

use List::MoreUtils;
use strict;
use warnings;
my @string = qw(a a a a b b b c d e f q q q r r r);
my @singletons = uniq(@string);

> where @singletons is a list of the elements in @string which occur only once. Note, however, that this operates on lists, not strings, so you'll have to split the string.

One A second way (guaranteed to be non-optimal &grin;) is to split the string into an array and count the occurences of each character.

use strict;use warnings; # because it's a really good idea my @string = split(//, 'aabbccddeeffgghhi'); my %count; foreach(@string) { $count{$_} ++; } foreach (keys(%count)) { print "$_ is unique\n" if $count{$_} == 1; }

I'm quite sure some of the regex gurus can do it with a single regex; I tend more to the "brute force and ignorance"™ school of programming than the "subtle and brilliant" school.


added in another update

As Hofmator pointed out, I screwed up: uniq doesn't return a list of elements that occur once in the original list; it returns a list with duplicates stripped out. That's why I've struck out a much of this post.

added in update

I knew that somebody would find a one-line solution.

emc

Experience is a hard teacher because she gives the test first, the lesson afterwards.

Vernon Sanders Law

Replies are listed 'Best First'.
Re^2: Unique character in a string?
by Hofmator (Curate) on Aug 10, 2006 at 06:23 UTC
    my @string = qw(a a a a b b b c d e f q q q r r r); my @singletons = uniq(@string);
    where @singletons is a list of the elements in @string which occur only once.
    This is not true, uniq removes duplicates from an array. From the doc:
    uniq LIST Returns a new list by stripping duplicate values in LIST. The order of elements in the returned list is the same as in LIST. In scalar context, returns the number of unique elements in LIST. my @x = uniq 1, 1, 2, 2, 3, 5, 3, 4; # returns 1 2 3 5 4

    -- Hofmator