Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Truncate string to 7 characters

Status
Not open for further replies.

nawlej

Programmer
Mar 26, 2004
380
US
What is the easiest way to truncate a string down to 7 characters? I have a string, which can contain letters, numbers, underscores,dashes, etc etc....that needs to be formatted down. Any ideas?
 
I did s/(\D\D\D\D\D\D\D)(.*)/$1/;

Better way??
 
Or how about:
Code:
$str = qq{123456789};
$str = substr($str,0,7);
print "$str\n";
Cheers, Neil
 
Am I missing something here? Why wouldn't you just use sprintf?
 
True, you can use:
Code:
$str = sprintf("%.7s", $str);
Buyt why not use substr? That's what its for. [thumbsup]
 
All good ideas.....I went with substr, I needed the variable for other things than print.
 
Here's a fun way to do it (untested).

my @array = split(//, $string);

my $count = -1;
my $newstring;

for ( 1 .. 7 )
{
$count++;
$newstring = $newstring . $array[$count];
}

print $newstring;



:)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top