在 Perl 6 中更改字符串中的一个字母

Change one letter in a string in Perl 6

应该很简单,但是我没有用.comb做一个list就找不到乐器来做。 我有一个 $string 和一个 (0 < $index < $string.chars - 1)。我需要制作一个 $new_string,其编号为 $index 的元素将更改为 'A'.

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

要仅更改字符串中的单个字母,您可以使用 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'

:nth 的 "indexing" 从 1 开始。 :nth 的真正含义是 "replace nth match alone"。因为我们的正则表达式只匹配一个字符,所以 :nth 就像一个索引(即使它在技术上不是)。

这是我推荐使用的:

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

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

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

如果您想远离变异操作:

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