tags:

views:

273

answers:

3

Write a function that returns the first non-repeating character in a string. Example: “Thanks for visiting" returns "h".

+2  A: 
sub get_char {
    my $string = shift;
    my @chars = split //, $string;        

    for my $i (0..$#chars) {
        return $chars[$i] if !grep { lc $chars[$i] eq lc } @chars[$i+1..$#chars];
    }
}
eugene y
+2  A: 
sub { 
    # This assumes non-repeating means consecutive-repeating.
    # non-consecutive-repeating is too boring to answer
    my $string_copy = $_[0];
    $string_copy =~ s/(.)(\1)+//g; 
    return substr($string_copy ,0, 1)
}  
DVK
This doesn't work on the OP's example.
mobrule
@mobrule - please see the comments on top :)For OP's example, the first non-consecutive-repeating character is "T", not "h". I didn't feel like answering his absolutely basic homework question that already has an answer posted and instead answered a somewhat more difficult one
DVK
+1  A: 
sub get_it {
    my $string = shift;
    for my $i ( 0 .. length($string) - 1 ) {
        my $char = substr $string, $i, 1;
        return $char if index( $string, $char, $i + 1 ) >= 0;
    }
}
Hynek -Pichi- Vychodil