in reply to Find First character of each word in a string

Why not try it yourself and then post your results and your code. Then mention problems that you encounter and errors.

Sweetblood

  • Comment on Re: Find First character of each word in a string

Replies are listed 'Best First'.
Re^2: Find First character of each word in a string
by kevyt (Scribe) on Nov 24, 2010 at 00:22 UTC
    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'
        Thanks