http://qs321.pair.com?node_id=16931

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question: (strings)

Example :
In the string "     " (5 chars long), add "A" at character 3 and "B" at character 2 to result in " BA  ".

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I insert characters at certain positions in a string?
by Anonymous Monk on Sep 16, 2003 at 22:28 UTC
    If you do not want to replace the character you can set the substring length to zero.
    my $padded = 'ABCDEFG'; substr($padded, 2, 0) = '1'; substr($padded, 1, 0) = '2';
    This will result in 'A2B1CDEFG'
Re: How do I insert characters at certain positions in a string?
by mdillon (Priest) on Jun 07, 2000 at 22:47 UTC
    my $padded = ' ' x 5; substr($padded, 2, 1) = 'A'; substr($padded, 1, 1) = 'B';
    Will result in: ' BA  '
Re: How do I insert characters at certain positions in a string?
by Anonymous Monk on Jan 15, 2002 at 10:14 UTC
    substr($string, $position, 0) = $what_you_want_inserted; where $string = the string you need to have something inserted into $position is where you want to have something inserted (a numerical value such as 0{for the first},1,2,3,4,5,etc) $what_you_want_inserted is what you want to insert in the string $string at position $position hope this helps

    Originally posted as a Categorized Answer.

Re: How do I insert characters at certain positions in a string?
by Anonymous Monk on Jan 15, 2002 at 09:48 UTC
    my $padded = ' ' x 5; substr($padded, 2, 1) = 'A'; substr($padded, 1, 1) = 'B'; now i tried this, and it just changed the Nth (2nd or 3rd) character it did not insert the character

    Originally posted as a Categorized Answer.