P is for Practical PerlMonks

### How do I cut single characters out of a string

by akechnie (Initiate)
 on Jan 13, 2012 at 19:03 UTC Need Help??
akechnie has asked for the wisdom of the Perl Monks concerning the following question:

Good Day,

I am working on string manipulation and am wondering how I can cut a single character from a larger string.

Example:

$string = "mystring123456"; #now I need to only cut number 1 from the middle #I tried using the below but I think I may be using it wrong$strleng = length($string);$getchar = substr($string,($strleng -6),($strleng -6)); print "string length is$strleng and character value is $getchar\n"; Any advice would be greatly appreciated Thanks Update included in the comments below :) • Comment on How do I cut single characters out of a string Replies are listed 'Best First'. Re: How do I cut single characters out of a string by toolic (Bishop) on Jan 13, 2012 at 19:17 UTC The substitution operator can remove a character: use warnings; use strict; my$string = "mystring123456";
$string =~ s/1//; print "$string\n";

__END__

mystring23456
[download]
Re: How do I cut single characters out of a string
by johngg (Abbot) on Jan 13, 2012 at 19:21 UTC

You can use index to find the position of the "1" and the four-argument form of substr to replace it.

knoppix@Microknoppix:~$perl -E ' >$str = q{mystring123456};
> substr $str, index($str, q{1} ), 1, q{};
> say $str;' mystring23456 knoppix@Microknoppix:~$
[download]

Cheers,

JohnGG

Re: How do I cut single characters out of a string
by Not_a_Number (Parson) on Jan 13, 2012 at 20:36 UTC

Ok, you've had three replies* (at the time of writing), all showing you how to remove '1' from a string.

Now, I might be wrong here (in which case read no further), but your use of a variable $getchar suggests that it might not be a known character that you want to remove from the string (and apparently save to a variable), but a character at a given position in the string. However, you say: now I need to only cut number 1 from the middle Which rather militates against my analysis: 1. Your example string is 14 characters long, and therefore has no single middle character. 2. The middle two characters are 'ng', but you say you want 'number 1 from the middle'. Whatever your real requirement, the following code removes and saves the middle character of a string if its length is odd, or the first of the two middle characters if its length is even: my$string = 'mystring123456'; # or whatever
my $getchar = substr$string, length( $string ) / 2, 1, ''; print "Character is$getchar and string is now $string\n"; [download] * One canonical, one rather needlessly complicated, and one that removes all '1's willy nilly. Re: How do I cut single characters out of a string by CountZero (Bishop) on Jan 13, 2012 at 20:59 UTC Two more: use List::MoreUtils qw/before after/; my$string = 'mystring123456';
$string = join '', (before {$_ eq 1} split //, $string), after {$_ eq
+1} split //, $string; [download] and my$string = 'mystring123456';
$string = join '', split /1/,$string, 2;
[download]
This last one is particularly nice: it allows you to delete the first one, first two, first three, ... characters just by changing the last number. To delete the first n occurrences, use n + 1 as the last argument of split.

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: How do I cut single characters out of a string
by pileofrogs (Priest) on Jan 13, 2012 at 22:07 UTC

Aaand just because everyone else is posting to this:

It all hinges on how you define what you are trying to remove. Is it the 1st instance of the number '1'? Is it the 1st digit in the string? Is it the 9th char from the beginning, the 6th from the end?

Some possible solutions:

$string =~ tr/1//d; [download] Will kill all the '1's w/out the regex engine. $string =~ s/\d//;
[download]

Will kill the very first digit found in a string

$char = substr($string,-6,1,'');
[download]

Will remove the 6th from the last char. substr treats negative numbers as offset from the end of the string, so you don't need to do (strlen -6).

etc... etc...

Re: How do I cut single characters out of a string
by CountZero (Bishop) on Jan 13, 2012 at 20:00 UTC
A most silly way to do it (but in the spirit of TIMTOWTDI):
my $string = 'mystring123456';$string = join '', grep {$_ ne 1} split //,$string;
[download]
And yes, this will cut all '1's out of the string.

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: How do I cut single characters out of a string
by tobyink (Abbot) on Jan 13, 2012 at 22:10 UTC

I'm surprised that nobody has mentioned that substr returns an lvalue. In other words, you can assign to it.

my $string = 'mystring123456'; substr($string, 8, 1) = '';
print "$string\n"; [download] Way back in the early days of Perl 5 substr didn't have the facility to supply a fourth argument so assigning to it as you describe was the only way to go. The advantage of using the 4-arg form to replace text is that what has been replaced is returned. Thus you can chain substrs together to move text around. knoppix@Microknoppix:~$ perl -E '
> $str = q{abcdefghijk}; > say$str;
> substr $str, 5, 2, substr$str, 3, 2, substr $str, 5, 2; > say$str;'
abcdefghijk
abcfgdehijk
knoppix@Microknoppix:~$perl -E ' [download] Of course, that particular example can be done more simply with a regex substitution but it can be a useful technique sometimes. knoppix@Microknoppix:~$ perl -E '
> $str = q{abcdefghijk}; > say$str;
> $str =~ s{^...\K(..)(..)}{$2$1}; > say$str;'
abcdefghijk
abcfgdehijk
knoppix@Microknoppix:~$[download] I hope this is of interest. Cheers, JohnGG substr$str, 5, 2, substr $str, 3, 2, substr$str, 5, 2;

I'll have to remember that next time I'm entering an obfuscated code contest.

Noone has mentioned that, but already 2 people before you used 4-arg substr, which in this case does the same thing.
Re: How do I cut single characters out of a string
by akechnie (Initiate) on Jan 16, 2012 at 00:28 UTC
Thank you all for your assistance so far. I've been working with this and have a temporary solution.

To clarify my script takes in a different value every time ie.
$string = "mystring654321"; I should have been more clear that the input will always have six numeric characters at the end. I need to find what the first characters value is. In this case it will be a "6" but could change the next time. My script then takes that value in and processes it further. in which case a simple regular expression match is probably what you want: if ($string =~ s/(\d)//) {
my $digit =$1;
...
} else {
print "No digit in '$string'\n"; } [download] which finds and removed the first digit from$string. Putting the substitution inside an if allows you to deal with not finding a digit.

True laziness is hard work
Ok I see what you did there
Now say I want the ability to grab any character out of the hole string given the position of it.

Such as mystring123456 so when I find the length of it with length(), so 14 characters. Is there a way I can tell it I want the 6th and 7th characters. Or then just grab the 9th character.

#not actual code more just a logical walk through
if(the string has 20 characters){
Get the 9th character;
Get the characters 6-8;
}elsif(the string has 14 characters){
Get the 6th character from the end;
Get the last 4 characters from the end;
}

Sorry if this looks ugly but sometimes it helps me think through things like this.

Create A New User
Node Status?
node history
Node Type: perlquestion [id://947795]
Approved by toolic
help
Chatterbox?
 [thezip]: So I have a script that generates a log file. After script completion, I want tohave VIM open this logfile. [thezip]: i don't get the command line "back" until I close VIM. No what I want to happen... [thezip]: I currently don't have access to CYGWIN, else I'd just do a tail -f on the logfile. [Corion]: thezip: If you want to open vim and can live with opening a second console window, use start "The results" vim.exe c:\path\to\logfile .log [thezip]: Ooops... I lied. I guess Cygwin is back. I'll just do a tail -f instead. Better. Sorry for the noise.

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (12)
As of 2017-03-27 18:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Should Pluto Get Its Planethood Back?

Results (321 votes). Check out past polls.