Substring/Top and tail: Difference between revisions
({{header|ZX Spectrum Basic}}) |
({{header|Perl}}) |
||
Line 9: | Line 9: | ||
=={{header|ZX Spectrum Basic}}== |
=={{header|ZX Spectrum Basic}}== |
||
<lang zxbasic> |
<lang zxbasic>10 PRINT FN f$("knight"): REM strip the first letter |
||
10 PRINT FN f$("knight"): REM strip the first letter |
|||
20 PRINT FN l$("socks"): REM strip the last letter |
20 PRINT FN l$("socks"): REM strip the last letter |
||
30 PRINT FN b$("brooms"): REM strip both the first and last letter |
30 PRINT FN b$("brooms"): REM strip both the first and last letter |
||
Line 17: | Line 16: | ||
9000 DEF FN f$(a$)=a$(2 TO LEN(a$)) |
9000 DEF FN f$(a$)=a$(2 TO LEN(a$)) |
||
9010 DEF FN l$(a$)=a$(1 TO LEN(a$)-(1 AND (LEN(a$)>=1))) |
9010 DEF FN l$(a$)=a$(1 TO LEN(a$)-(1 AND (LEN(a$)>=1))) |
||
9020 DEF FN b$(a$)=FN l$(FN f$(a$)) |
9020 DEF FN b$(a$)=FN l$(FN f$(a$)) </lang> |
||
</lang> |
|||
=={{header|Perl}}== |
|||
<lang perl>print substr("knight",1), "\n"; # strip first character |
|||
print substr("socks", 0, -1), "\n"; # strip last character |
|||
print substr("brooms", 1, -1), "\n"; # strip both first and last characters</lang> |
|||
In perl, we can also remove the last character from a string variable with the chop function: |
|||
<lang perl>$string = 'ouch'; |
|||
$bits = chop($string); # The last letter is returned by the chop function |
|||
print $bits; # h |
|||
print $string; # ouc # See we really did chop the last letter off</lang> |
|||
[[Category:String manipulation]] |
[[Category:String manipulation]] |
Revision as of 23:15, 5 June 2011
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results:
- String with first character removed
- String with last character removed
- String with both the first and last characters removed
ZX Spectrum Basic
<lang zxbasic>10 PRINT FN f$("knight"): REM strip the first letter 20 PRINT FN l$("socks"): REM strip the last letter 30 PRINT FN b$("brooms"): REM strip both the first and last letter 100 STOP
9000 DEF FN f$(a$)=a$(2 TO LEN(a$)) 9010 DEF FN l$(a$)=a$(1 TO LEN(a$)-(1 AND (LEN(a$)>=1))) 9020 DEF FN b$(a$)=FN l$(FN f$(a$)) </lang>
Perl
<lang perl>print substr("knight",1), "\n"; # strip first character print substr("socks", 0, -1), "\n"; # strip last character print substr("brooms", 1, -1), "\n"; # strip both first and last characters</lang>
In perl, we can also remove the last character from a string variable with the chop function:
<lang perl>$string = 'ouch'; $bits = chop($string); # The last letter is returned by the chop function print $bits; # h print $string; # ouc # See we really did chop the last letter off</lang>