Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change one letter in a string in Perl 6

Tags:

raku

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'
like image 361
Eugene Barsky Avatar asked Oct 29 '25 17:10

Eugene Barsky


2 Answers

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
like image 143
Brad Gilbert Avatar answered Oct 31 '25 10:10

Brad Gilbert


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).

like image 34
callyalater Avatar answered Oct 31 '25 10:10

callyalater



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!