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

Find First character of each word in a string

by kevyt (Scribe)
on Nov 23, 2010 at 23:44 UTC ( #873317=perlquestion: print w/ replies, xml ) Need Help??
kevyt has asked for the wisdom of the Perl Monks concerning the following question:

I am embarrassed to ask such a simple question but I haven't coded much in the last few years and I forgot a few things. I would like to abbreviate a string such as "Internal Computing Department" to ICD. Can you help? I looked for the source code for ucfirst and I did not find anything helpful. I assume I could use a regular expression with a ^ to get the first Char and then | to get chars after a space. Thanks

Comment on Find First character of each word in a string
Re: Find First character of each word in a string
by sweetblood (Parson) on Nov 24, 2010 at 00:09 UTC
    Why not try it yourself and then post your results and your code. Then mention problems that you encounter and errors.

    Sweetblood

      This works but I dont like it.
      $str = 'my cardio workout'; @s = split (/\s/,$str); foreach (@s){ my $new_str = substr ($_,0,1); $new_str = ucfirst ($new_str); $ab .= $new_str; } print "AB is $ab\n";

        If that's the way things are, then maybe:

        >perl -wMstrict -le "my $str = 'eternal corruption defilement'; ;; $str =~ s{ \b ([[:alpha:]]) [[:lower:]]* \s* }{\U$1}xmsg; ;; print qq{'$str'}; " 'ECD'

        Update: Removed an unnecessary level of capture grouping in regex above. Also:  [[:lower:]]* might be better as  [[:alpha:]]* instead.

        Update: Or even:

        >perl -wMstrict -le "my $str = 'eternal corruption defilement'; ;; $str =~ s{ (\b [[:alpha:]]+ \s*) }{ uc substr $1, 0, 1 }xmsge; ;; print qq{'$str'}; " 'ECD'
Re: Find First character of each word in a string
by AnomalousMonk (Abbot) on Nov 24, 2010 at 00:15 UTC

    One possible approach:

    >perl -wMstrict -le "my $str = 'Internal Computing Department'; ;; $str =~ s{ [^[:upper:]] }{}xmsg; ;; print qq{'$str'}; " 'ICD'

    Update: Beyond that, maybe try what sweetblood suggests?

Re: Find First character of each word in a string
by ahmad (Hermit) on Nov 24, 2010 at 00:51 UTC

    There are more than one way to do it, here are some I can think of:

    my $str = 'Internal Computing Department'; my $res = join '' , map {(split //,$_)[0]} split /\s/, $str; # OR my $res = join '' , map { substr $_, 0 , 1 } split /\s/, $str; # OR my $res; $res .= $1 while ( $str=~m/(\S)\S+/g ); print $res;
Re: Find First character of each word in a string
by LanX (Canon) on Nov 24, 2010 at 00:55 UTC
    DB<1> $str="Internal Computing Department" DB<2> print $str=~m/\b(\w)/g ICD

    UPDATE

    nota bene, the regex returned a list not a string!

    if you want to uppercase it try uc after joining.

    DB<15> $abbr= uc join "","internal computing department" =~ m/\b(\w) +/g DB<16> print $abbr ICD

    Cheers Rolf

      Thanks

      But:

      DB<3> print 'my cardio workout' =~ m/\b\w/g; mcw

      Maybe:

      DB<4> print map uc, 'my cardio workout' =~ m/\b\w/g; MCW

      Update: Oops: LanX beat me to the punch.

Re: Find First character of each word in a string
by GrandFather (Sage) on Nov 24, 2010 at 02:24 UTC

    A Perlish version might look something like:

    #!/usr/bin/perl use strict; use warnings; my $str = "Internal Computing Department"; print join '', map {uc substr $_, 0, 1} split ' ', $str;

    Prints:

    ICD
    True laziness is hard work
Re: Find First character of each word in a string
by biohisham (Priest) on Nov 24, 2010 at 06:58 UTC
    Backreferencing is just another way to go
    $string = "Internal Computing Department"; $string =~ s/(\w)\w*/$1\./g; print $string ; #OUTPUT I. C. D.



    Excellence is an Endeavor of Persistence. A Year-Old Monk :D .
Re: Find First character of each word in a string
by sundialsvc4 (Abbot) on Nov 24, 2010 at 16:08 UTC

    perl -e 'my $foo="Internal computing\n department."; while ($foo =~ /(\w+)/g) {print substr($1, 0,1)."\n";}'

    prints:
    I
    c
    d

    Note that the /g qualifier is critical.   (If this modifier is omitted, the program will loop endlessly, printing “I.”)   Also review the meanings of the /s, /p, and /m qualifiers, and of the “?” (“non-greedy”) symbol in the pattern string.   Ponder this:   “pos($foo) = undef;.”

    The answer is:   “regular expressions.”
    Now then, what’s the question?

Re: Find First character of each word in a string
by phenom (Chaplain) on Nov 24, 2010 at 16:28 UTC

    Another one liner way:

    perl -e 'print uc substr( $_, 0, 1 ) for split(/\s+/, shift())' "Inter +nal Computing Department"

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://873317]
Approved by sweetblood
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (6)
As of 2015-07-07 02:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (86 votes), past polls