There are a couple of things to think about here. You need to figure out how you are going to store the word spans (where do they come from btw?). Deciding just what is a word can be tricky (e.g. for example).

When editing involves changing the length of whatever is being edited it is often better to work backwards so that you don't change the indexes for subsequent edits. The following somewhat golfed code (don't hand it in to your teacher) counts words by counting the spans of spaces between them:

use strict; use warnings; my $sentence = 'Sam goes to school to play football.'; my @subs = ([12, 17], [27, 34]); my @counts; @subs = sort {$b->[0] <=> $a->[0]} @subs; # Descending sort by first c +har pos for my $sub (@subs) { unshift @counts, 1 + (substr $sentence, 0, $sub->[0]) =~ s/(\s+)/$ +1/g; substr $sentence, $_, 0, '**' for $sub->[1] + 1, $sub->[0]; } print "@counts $sentence\n";

Prints:

4 7 Sam goes to **school** to play **football**.

Perl reduces RSI - it saves typing

In reply to Re: character offset to word offset by GrandFather
in thread character offset to word offset by newbio

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.