Eugene Barsky
Eugene Barsky

Reputation: 6012

Change one letter in a string in Perl 6

It should be very simple, but I can't find an instrument to do it without making a list with .comb. I have a $string and an (0 < $index < $string.chars - 1). I need to make a $new_string, whose element with number $index will be changed, say, to 'A'.

my $string = 'abcde';
my $index = 0; # $new_string should be 'Abcde'
my $index = 3; # $new_string should be 'abcAe'

Upvotes: 4

Views: 532

Answers (2)

Brad Gilbert
Brad Gilbert

Reputation: 34120

This is what I would recommend using:

my $string = 'abcde';
my $index = 0;

( my $new-string = $string ).substr-rw( $index, 1 ) = 'A';

say $string;     # abcde
say $new-string; # Abcde

If you wanted to stay away from a mutating operation:

sub string-index-replace (
  Str $in-str,
  UInt $index,
  Str $new where .chars == 1
){

  ( # the part of the string before the value to insert
    $in-str.substr( 0, $index ) xx? $index
  )
  ~
  ( # add spaces if the insert is beyond the end of the string
    ' ' x $index - $in-str.chars
  )
  ~
  $new
  ~
  ( # the part of the string after the insert
    $in-str.substr( $index + 1 ) xx? ( $index < $in-str.chars)
  )
}

say string-index-replace( 'abcde', $_, 'A' ) for ^10
Abcde
aAcde
abAde
abcAe
abcdA
abcdeA
abcde A
abcde  A
abcde   A
abcde    A

Upvotes: 3

callyalater
callyalater

Reputation: 3102

To change just a single letter in the string, you can use the subst method on type Str:

my $string = 'abcde';
my $index = 0;
my $new_string = $string.subst: /./, 'A', :nth($index+1); # 'Abcde'
$index = 3;
$new_string = $string.subst: /./, 'A', :nth($index+1);    # 'abcAe'

The "indexing" for :nth starts at 1. What :nth really means is "replace nth match alone". Because our regex only matches a single character, :nth acts like an index (even though it technically is not).

Upvotes: 2

Related Questions