Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: character offset to word offset

by betterworld (Curate)
on Sep 08, 2008 at 19:09 UTC ( [id://709838]=note: print w/replies, xml ) Need Help??


in reply to character offset to word offset

I'm not sure I understand correctly what you want to do, but I'll try:

my $sentence = 'Sam goes to school to play football.'; substr($sentence, $_, 0) = '**' for 35, 27, 18, 12; print $sentence, "\n";

This will print Sam goes to **school** to play **football**., and the asterisks have been put there using the character offsets.

However, a more straightforward way to highlight school this way would be something like:

$sentence =~ s/(school)/**\1**/;

Update: Sorry, I forgot the part about the word count.. Well, here's a way to get to the "4" (not very nice, maybe others have a more beautiful solution):

my $sentence = 'Sam goes to school to play football.'; # Count the spaces and add 1 my $count1 = substr($sentence, 0, 12) =~ y/ // + 1;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (5)
As of 2024-04-16 17:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found