javaGirl
javaGirl

Reputation: 195

How do I remove characters from a string at a certain position?

I have the variables $pos, $toRemove and $line. I would like to remove from this string $toRemove from position $pos.

$line = "Hello kitty how are you kitty kitty nice kitty";
$toRemove = "kitty";
$pos = 30; # the 3rd 'kitty'

I want to check if from position 30 there is string kitty and I want to remove exactly this one.

Could you give me a solution of that? I can do it using a lot of loops and variables but it looks strange and works really slow.

Upvotes: 4

Views: 4210

Answers (5)

Borodin
Borodin

Reputation: 126722

The [pos][pos] operator is an lvalue for just this sort of thing:

[pos]:

use strict;
use warnings;

my $line = "Hello kitty how are you kitty kitty nice kitty";
my $toRemove = "kitty";
my $pos = 30;

pos($line) = $pos;

$line =~ s/\G$toRemove//;

print $line;

output

Hello kitty how are you kitty  nice kitty

Upvotes: 1

dan1111
dan1111

Reputation: 6566

$line =~ s/^.{30}\K$toRemove//;

This uses a look-behind assertion to match the first 30 characters without including them in the part of the pattern that is replaced.

Upvotes: 2

lollo
lollo

Reputation: 2307

Yet another way:

$line = "Hello kitty how are you kitty kitty nice kitty";
$toRemove = "kitty";
$pos = 30;

$line =~ s/(.{$pos})$toRemove/$1/;
print $line;

result:

Hello kitty how are you kitty  nice kitty

Upvotes: 2

cdtits
cdtits

Reputation: 1128

$line = "Hello kitty how are you kitty kitty nice kitty";
$toRemove = "kitty";
$pos = 30; # the 3rd 'kitty'

pos($line) = $pos;
$line =~ s/\G$toRemove//gc;
print $line;

output:

Hello kitty how are you kitty  nice kitty

Upvotes: 3

CyberDem0n
CyberDem0n

Reputation: 15036

if (substr($line, $pos, length($toRemove)) eq $toRemove) {
    substr($line, $pos, length($toRemove)) = "";
}

Upvotes: 6

Related Questions