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 Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

getting first char of a string

Status
Not open for further replies.

jimberger

Programmer
Jul 5, 2001
222
GB
Hello all,

I have a string e,g test

how do i retrieve the first character of that string

for example a function that takes a string test and returns the letter t

Thanks for your help

jimbob
 
The function substring take any part of a string. Its syntax is :

substr(expression, nb_of_char_to_jump, nb_of_char_to_extract);

For example, your string $string="test". you want the 't' do:
$first_letter=substr($string,0,1);

0 : means that you don'nt want to skip any char
1 : means that you need only 1 char

 
If you're familiar with regexs you can also try:

$string =~ /^(.{1,1})/;
$letter = $1;

The "{1,1}" specifies only 1 character. If you want 2 or 3 characters you would change it to "{2,3}". This method is quicker than substr.

HTH,
Barbie. Leader of Birmingham Perl Mongers
 
You could also do

@char_array = split //, $string_of_text;

$first_char = @char_array[0];

When you split on nothing(//), it splits each character into it's own element of the resulting list. I'm not sure how efficient this is compared to the other methods, but this is an option.

HTH. Hardy Merrill
Mission Critical Linux, Inc.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top