Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

substring

perl

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.

like image 810
javaGirl Avatar asked Dec 09 '22 22:12

javaGirl


2 Answers

if (substr($line, $pos, length($toRemove)) eq $toRemove) {
    substr($line, $pos, length($toRemove)) = "";
}
like image 146
CyberDem0n Avatar answered Mar 16 '23 00:03

CyberDem0n


$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
like image 33
cdtits Avatar answered Mar 15 '23 23:03

cdtits