Substring/Top and tail: Difference between revisions

From Rosetta Code
Content added Content deleted
(39 intermediate revisions by 26 users not shown)
Line 1: Line 1:
{{task}}
{{task}}[[Category:String manipulation]]
[[Category:String manipulation]]
The task is to demonstrate how to remove the first and last characters from a string.
The task is to demonstrate how to remove the first and last characters from a string.


Line 14: Line 15:


Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.
Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.


{{Template:Strings}}
<br><br>
<br><br>

=={{header|11l}}==
{{trans|Python}}

<syntaxhighlight lang="11l">print(‘knight’[1..])
print(‘socks’[0 .< (len)-1])
print(‘brooms’[1 .< (len)-1])</syntaxhighlight>

{{out}}
<pre>
night
sock
room
</pre>


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
<lang 360asm>* Substring/Top and tail 04/03/2017
<syntaxhighlight lang="360asm">* Substring/Top and tail 04/03/2017
SUBSTRTT CSECT
SUBSTRTT CSECT
USING SUBSTRTT,R13 base register
USING SUBSTRTT,R13 base register
Line 43: Line 61:
S6 DS CL6
S6 DS CL6
YREGS
YREGS
END SUBSTRTT</lang>
END SUBSTRTT</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 53: Line 71:


=={{header|ACL2}}==
=={{header|ACL2}}==
<lang Lisp>(defun str-rest (str)
<syntaxhighlight lang="lisp">(defun str-rest (str)
(coerce (rest (coerce str 'list)) 'string))
(coerce (rest (coerce str 'list)) 'string))


Line 67: Line 85:
(str-rdc "string")
(str-rdc "string")
(str-rest "string")
(str-rest "string")
(str-rest (str-rdc "string"))</lang>
(str-rest (str-rdc "string"))</syntaxhighlight>

=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Main()
CHAR ARRAY text="qwertyuiop"
CHAR ARRAY res(20)
BYTE n,m

PrintF("Original string:%E ""%S""%E%E",text)

SCopyS(res,text,2,text(0))
PrintF("String without the top:%E ""%S""%E%E",res)

SCopyS(res,text,1,text(0)-1)
PrintF("String without the tail:%E ""%S""%E%E",res)

SCopyS(res,text,2,text(0)-1)
PrintF("String without the top and the tail:%E ""%S""%E%E",res)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Top_and_tail.png Screenshot from Atari 8-bit computer]
<pre>
Original string:
"qwertyuiop"

String without the top:
"wertyuiop"

String without the tail:
"qwertyuio"

String without the top and the tail:
"wertyuio"
</pre>


=={{header|Ada}}==
=={{header|Ada}}==


<lang Ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;


procedure Remove_Characters is
procedure Remove_Characters is
Line 81: Line 132:
Put_Line("Without_Last: """ & S(S'First .. S'Last-1) & """");
Put_Line("Without_Last: """ & S(S'First .. S'Last-1) & """");
Put_Line("Without_Both: """ & S(S'First+1 .. S'Last-1) & """");
Put_Line("Without_Both: """ & S(S'First+1 .. S'Last-1) & """");
end Remove_Characters;</lang>
end Remove_Characters;</syntaxhighlight>


Output:
Output:
Line 92: Line 143:
With UTF8 support in Ada 2012 (Wide_Character of literals is automatic):
With UTF8 support in Ada 2012 (Wide_Character of literals is automatic):


<lang Ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;
with Ada.Strings.UTF_Encoding.Wide_Strings;
with Ada.Strings.UTF_Encoding.Wide_Strings;


Line 124: Line 175:
("Without_Both: """ & U (U'First + 1 .. U'Last - 1) & """"));
("Without_Both: """ & U (U'First + 1 .. U'Last - 1) & """"));


end Remove_Characters;</lang>
end Remove_Characters;</syntaxhighlight>


Output:
Output:
Line 134: Line 185:


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>o_text(delete("knights", 0));
<syntaxhighlight lang="aime">o_text(delete("knights", 0));
o_newline();
o_newline();
o_text(delete("knights", -1));
o_text(delete("knights", -1));
o_newline();
o_newline();
o_text(delete(delete("knights", 0), -1));
o_text(delete(delete("knights", 0), -1));
o_newline();</lang>
o_newline();</syntaxhighlight>
{{out}}
{{out}}
<pre>nights
<pre>nights
Line 150: Line 201:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
<lang algol68>#!/usr/local/bin/a68g --script #
<syntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script #


STRING str="upraisers";
STRING str="upraisers";
Line 163: Line 214:
str[LWB str+2:UPB str-1], # remove 2 before and one after #
str[LWB str+2:UPB str-1], # remove 2 before and one after #
str[LWB str+2:UPB str-2] # remove both the first and last 2 characters #
str[LWB str+2:UPB str-2] # remove both the first and last 2 characters #
))</lang>
))</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 175: Line 226:
raiser
raiser
raise
raise
</pre>

=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
#include <hopper.h>
#proto showmessage(_X_)
main:
s="message", t=s
++s, _show message(s)
s=t
--s, _show message(s)
++s, _show message(s)
{0}return

.locals
showmessage(_S_)
{_S_,"\n"}print
back
</syntaxhighlight>
{{out}}
<pre>
essage
messag
essag
</pre>
</pre>


=={{header|Apex}}==
=={{header|Apex}}==
<lang java>
<syntaxhighlight lang="java">
String strOrig = 'brooms';
String strOrig = 'brooms';
String str1 = strOrig.substring(1, strOrig.length());
String str1 = strOrig.substring(1, strOrig.length());
Line 195: Line 270:
String str3 = strOrig.replaceAll( '^.|.$', '' );
String str3 = strOrig.replaceAll( '^.|.$', '' );
system.debug(str3);
system.debug(str3);
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 208: Line 283:
=={{header|AppleScript}}==
=={{header|AppleScript}}==


<lang applescript>set aString to "This is some text"
<syntaxhighlight lang="applescript">set aString to "This is some text"


set stringLength to (count aString) -- The number of characters in the text.
set stringLength to (count aString) -- The number of characters in the text.
Line 236: Line 311:
end if
end if


return substring1 & linefeed & substring2 & linefeed & substring3</lang>
return substring1 & linefeed & substring2 & linefeed & substring3</syntaxhighlight>


{{output}}
{{output}}
Line 242: Line 317:
This is some tex
This is some tex
his is some tex"</pre>
his is some tex"</pre>

=={{header|Arturo}}==

<syntaxhighlight lang="rebol">knight: "knight"
socks: "socks"
brooms: "brooms"

print drop knight. ; strip first character
print slice knight 1 (size knight)-1 ; alternate way to strip first character

print chop socks ; strip last character
print take socks (size socks)-1 ; alternate way to strip last character
print slice socks 0 (size socks)-2 ; yet another way to strip last character

print chop drop brooms ; strip both first and last characters
print slice brooms 1 (size brooms)-2 ; alternate way to strip both first and last characters</syntaxhighlight>

{{out}}

<pre>night
night
sock
sock
sock
room
room</pre>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>myString := "knights"
<syntaxhighlight lang="autohotkey">myString := "knights"
MsgBox % SubStr(MyString, 2)
MsgBox % SubStr(MyString, 2)
MsgBox % SubStr(MyString, 1, StrLen(MyString)-1)
MsgBox % SubStr(MyString, 1, StrLen(MyString)-1)
MsgBox % SubStr(MyString, 2, StrLen(MyString)-2)</lang>
MsgBox % SubStr(MyString, 2, StrLen(MyString)-2)</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<lang awk>BEGIN {
<syntaxhighlight lang="awk">BEGIN {
mystring="knights"
mystring="knights"
print substr(mystring,2) # remove the first letter
print substr(mystring,2) # remove the first letter
print substr(mystring,1,length(mystring)-1) # remove the last character
print substr(mystring,1,length(mystring)-1) # remove the last character
print substr(mystring,2,length(mystring)-2) # remove both the first and last character
print substr(mystring,2,length(mystring)-2) # remove both the first and last character
}</lang>
}</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
<lang basic>10 PRINT FN F$("KNIGHTS"): REM STRIP THE FIRST LETTER
<syntaxhighlight lang="basic">10 PRINT FN F$("KNIGHTS"): 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 265: Line 366:
9000 DEF FN F$(A$)=RIGHT$(A$,LEN(A$)-1)
9000 DEF FN F$(A$)=RIGHT$(A$,LEN(A$)-1)
9010 DEF FN L$(A$)=LEFT$(A$,LEN(A$)-1)
9010 DEF FN L$(A$)=LEFT$(A$,LEN(A$)-1)
9020 DEF FN B$(A$)=FN L$(FN F$(A$))</lang>
9020 DEF FN B$(A$)=FN L$(FN F$(A$))</syntaxhighlight>

==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="qbasic">10 s$ = "Rosetta Code"
20 PRINT s$
30 PRINT MID$(s$,2)
40 PRINT LEFT$(s$,LEN(s$)-1)
50 PRINT MID$(s$,2,LEN(s$)-2) </syntaxhighlight>

==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="qbasic">10 s$ = "Rosetta Code"
20 print s$
30 print mid$(s$,2)'strip first
40 print left$(s$,len(s$)-1)'strip last
50 print mid$(s$,2,len(s$)-2)'strip first and last</syntaxhighlight>

==={{header|MSX Basic}}===
{{works with|GW-BASIC}}
<syntaxhighlight lang="qbasic">10 S$ = "Rosetta Code"
20 PRINT S$
30 PRINT MID$(S$, 2) 'strip first
40 PRINT LEFT$(S$, LEN(S$) - 1) 'strip last
50 PRINT MID$(S$, 2, LEN(S$) - 2) 'strip first and last</syntaxhighlight>

==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasic">s$ = "Rosetta Code"

PRINT s$
PRINT MID$(s$, 2) 'strip first
PRINT LEFT$(s$, LEN(s$) - 1) 'strip last
PRINT MID$(s$, 2, LEN(s$) - 2) 'strip first and last</syntaxhighlight>

==={{header|BASIC256}}===
<syntaxhighlight lang="freebasic">s$ = "Rosetta Code"

print s$
PRINT MID$(s$, 2) 'strip first
PRINT LEFT$(s$, LEN(s$) - 1) 'strip last
PRINT MID$(s$, 2, LEN(s$) - 2) 'strip first and last</syntaxhighlight>

==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">LET s$ = "Rosetta Code"
PRINT s$
PRINT (s$)[2:maxnum] !strip first
PRINT (s$)[1:len(s$)-1] !strip last
PRINT (s$)[2:2+len(s$)-2-1] !strip first and last
END</syntaxhighlight>

==={{header|XBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">PROGRAM "Substring"
VERSION "0.0000"

DECLARE FUNCTION Entry ()

FUNCTION Entry ()
s$ = "Rosetta Code"

PRINT s$
PRINT MID$(s$, 2) 'strip first
PRINT LEFT$(s$, LEN(s$) - 1) 'strip last
PRINT MID$(s$, 2, LEN(s$) - 2) 'strip first and last

END FUNCTION
END PROGRAM</syntaxhighlight>

==={{header|Yabasic}}===
<syntaxhighlight lang="freebasic">s$ = "Rosetta Code"

print s$
PRINT MID$(s$, 2) 'strip first
PRINT LEFT$(s$, LEN(s$) - 1) 'strip last
PRINT MID$(s$, 2, LEN(s$) - 2) 'strip first and last</syntaxhighlight>


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 LET S$="Knights"
<syntaxhighlight lang="is-basic">100 LET S$="Knights"
110 PRINT S$(2:)
110 PRINT S$(2:)
120 PRINT S$(:LEN(S$)-1)
120 PRINT S$(:LEN(S$)-1)
130 PRINT S$(2:LEN(S$)-1)</lang>
130 PRINT S$(2:LEN(S$)-1)</syntaxhighlight>


==={{header|Sinclair ZX81 BASIC}}===
==={{header|Sinclair ZX81 BASIC}}===
Note that strings are indexed from 1.
Note that strings are indexed from 1.
<lang basic>10 REM STRING SLICING EXAMPLE
<syntaxhighlight lang="basic">10 REM STRING SLICING EXAMPLE
20 LET S$="KNIGHTS"
20 LET S$="KNIGHTS"
30 REM WITH FIRST CHARACTER REMOVED:
30 REM WITH FIRST CHARACTER REMOVED:
Line 282: Line 458:
60 PRINT S$( TO LEN S$-1)
60 PRINT S$( TO LEN S$-1)
70 REM WITH BOTH REMOVED:
70 REM WITH BOTH REMOVED:
80 PRINT S$(2 TO LEN S$-1)</lang>
80 PRINT S$(2 TO LEN S$-1)</syntaxhighlight>
{{out}}
{{out}}
<pre>NIGHTS
<pre>NIGHTS
KNIGHT
KNIGHT
NIGHT</pre>
NIGHT</pre>

==={{header|Microsoft Small Basic}}===
When I tried using Unicode characters, it printed question marks, though ASCII works fine.
<syntaxhighlight lang="vbnet">
string = "Small Basic"
TextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) 'Without the first character
TextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) 'Without the last character
TextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) 'Without the first and last characters
</syntaxhighlight>
{{out}}
<pre>
mall Basic
Small Basi
mall Basi
</pre>

=={{header|BQN}}==
Drop(<code>↓</code>) is the main function used here.

<syntaxhighlight lang="bqn"> str ← "substring"
"substring"
1↓str
"ubstring"
¯1↓str
"substrin"
1↓¯1↓str
"ubstrin"</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic> s$ = "Rosetta Code"
<syntaxhighlight lang="bbcbasic"> s$ = "Rosetta Code"
PRINT MID$(s$, 2)
PRINT MID$(s$, 2)
PRINT LEFT$(s$)
PRINT LEFT$(s$)
PRINT LEFT$(MID$(s$, 2))</lang>
PRINT LEFT$(MID$(s$, 2))</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
Bracmat uses UTF-8 internally. The function <code>utf</code> fails if its argument isn't a valid UTF-8 multibyte string, but in two slightly different ways: an indefinite and a definite way. If the argument does not have the required number of bytes but otherwise seems to be ok, Bracmat's backtacking mechanism lenghtens the argument and then calls <code>utf</code> again. This is repeated until utf either succeeds or definitely fails. The code is far from efficient.
Bracmat uses UTF-8 internally. The function <code>utf</code> fails if its argument isn't a valid UTF-8 multibyte string, but in two slightly different ways: an indefinite and a definite way. If the argument does not have the required number of bytes but otherwise seems to be ok, Bracmat's backtacking mechanism lenghtens the argument and then calls <code>utf</code> again. This is repeated until utf either succeeds or definitely fails. The code is far from efficient.


<lang bracmat>(substringUTF-8=
<syntaxhighlight lang="bracmat">(substringUTF-8=
@( Δημοτική
@( Δημοτική
: (%?a&utf$!a) ?"String with first character removed"
: (%?a&utf$!a) ?"String with first character removed"
Line 316: Line 519:
$ ( "String with both the first and last characters removed:"
$ ( "String with both the first and last characters removed:"
!"String with both the first and last characters removed"
!"String with both the first and last characters removed"
));</lang>
));</syntaxhighlight>


<pre>!substringUTF-8
<pre>!substringUTF-8
Line 325: Line 528:
If the string is known to consist of 8-byte characters, we can use a simpler method. Essential are the <code>%</code> and <code>@</code> prefixes. The <code>%</code> prefix matches 1 or more elements (bytes, in the case of string pattern matching), while <code>@</code> matches 0 or 1 elements. In combination these prefixes match 1 and only 1 byte.
If the string is known to consist of 8-byte characters, we can use a simpler method. Essential are the <code>%</code> and <code>@</code> prefixes. The <code>%</code> prefix matches 1 or more elements (bytes, in the case of string pattern matching), while <code>@</code> matches 0 or 1 elements. In combination these prefixes match 1 and only 1 byte.


<lang bracmat>(substring-8-bit=
<syntaxhighlight lang="bracmat">(substring-8-bit=
@("8-bit string":%@ ?"String with first character removed")
@("8-bit string":%@ ?"String with first character removed")
& @("8-bit string":?"String with last character removed" @)
& @("8-bit string":?"String with last character removed" @)
Line 338: Line 541:
$ ( "String with both the first and last characters removed:"
$ ( "String with both the first and last characters removed:"
!"String with both the first and last characters removed"
!"String with both the first and last characters removed"
));</lang>
));</syntaxhighlight>


<pre>!substring-8-bit
<pre>!substring-8-bit
Line 346: Line 549:


=={{header|Burlesque}}==
=={{header|Burlesque}}==
<lang blsq>
<syntaxhighlight lang="blsq">
blsq ) "RosettaCode"[-
blsq ) "RosettaCode"[-
"osettaCode"
"osettaCode"
Line 357: Line 560:
blsq ) "RosettaCode"~-
blsq ) "RosettaCode"~-
"osettaCod"
"osettaCod"
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <string.h>
<syntaxhighlight lang="c">#include <string.h>
#include <stdlib.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
Line 384: Line 587:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


Result:
Result:
Line 394: Line 597:


=={{header|C sharp}}==
=={{header|C sharp}}==
<lang C sharp>
<syntaxhighlight lang="c sharp">
using System;
using System;


Line 407: Line 610:
}
}
}
}
</syntaxhighlight>
</lang>


Result:
Result:
Line 415: Line 618:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <string>
<syntaxhighlight lang="cpp">#include <string>
#include <iostream>
#include <iostream>


Line 424: Line 627:
std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ;
std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ;
return 0 ;
return 0 ;
}</lang>
}</syntaxhighlight>
Output:
Output:
<PRE>Without first letter: remier League !
<PRE>Without first letter: remier League !
Line 432: Line 635:


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>; using substring:
<syntaxhighlight lang="clojure">; using substring:
user=> (subs "knight" 1)
user=> (subs "knight" 1)
"night"
"night"
Line 446: Line 649:
"sock"
"sock"
user=> (apply str (rest (drop-last "brooms")))
user=> (apply str (rest (drop-last "brooms")))
"room"</lang>
"room"</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang COBOL> identification division.
<syntaxhighlight lang="cobol"> identification division.
program-id. toptail.
program-id. toptail.


Line 465: Line 668:
display data-field(2:length of data-field - 2)
display data-field(2:length of data-field - 2)
goback.
goback.
end program toptail.</lang>
end program toptail.</syntaxhighlight>


{{out}}
{{out}}
Line 476: Line 679:
=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<code>subseq</code> will signal an error if you provide invalid start or end values.
<code>subseq</code> will signal an error if you provide invalid start or end values.
<lang lisp>> (defvar *str* "∀Ꮺ✤Л◒")
<syntaxhighlight lang="lisp">> (defvar *str* "∀Ꮺ✤Л◒")
*STR*
*STR*
> (subseq *str* 1) ; remove first character
> (subseq *str* 1) ; remove first character
Line 483: Line 686:
"∀Ꮺ✤Л"
"∀Ꮺ✤Л"
> (subseq *str* 1 (1- (length *str*))) ; remove first and last character
> (subseq *str* 1 (1- (length *str*))) ; remove first and last character
"Ꮺ✤Л"</lang>
"Ꮺ✤Л"</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
Version for ASCII strings or Unicode dstrings:
Version for ASCII strings or Unicode dstrings:
<lang d>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;


void main() {
void main() {
Line 498: Line 701:
// strip both first and last characters
// strip both first and last characters
writeln("brooms"[1 .. $ - 1]);
writeln("brooms"[1 .. $ - 1]);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>night
<pre>night
sock
sock
room</pre>
room</pre>

=={{header|Dart}}==
<syntaxhighlight lang="dart">void main() {
String word = "Premier League";
print("Without first letter: ${word.substring(1)} !");
print("Without last letter: ${word.substring(0, word.length - 1)} !");
print("Without first and last letter: ${word.substring(1, word.length - 1)} !");
}</syntaxhighlight>
{{out}}
<pre>Same as C++ entry.</pre>


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>program TopAndTail;
<syntaxhighlight lang="delphi">program TopAndTail;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 518: Line 731:


Readln;
Readln;
end.</lang>
end.</syntaxhighlight>

=={{header|EasyLang}}==
<syntaxhighlight>
s$ = "Easylang"
print substr s$ 1 (len s$ - 1)
print substr s$ 2 (len s$ - 1)
print substr s$ 2 (len s$ - 2)
</syntaxhighlight>
{{out}}
<pre>
Easylan
asylang
asylan
</pre>


=={{header|Eero}}==
=={{header|Eero}}==
<lang objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>


int main()
int main()
Line 538: Line 765:
Log( '%@', s[1 .. s.length-2] ) // strip both first and last characters
Log( '%@', s[1 .. s.length-2] ) // strip both first and last characters


return 0</lang>
return 0</syntaxhighlight>


Output:<pre>
Output:<pre>
Line 548: Line 775:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x :
ELENA 4.x :
<lang elena>import extensions;
<syntaxhighlight lang="elena">import extensions;
public program()
public program()
Line 557: Line 784:
console.printLine(testString.Substring(0, testString.Length - 1));
console.printLine(testString.Substring(0, testString.Length - 1));
console.printLine(testString.Substring(1, testString.Length - 2))
console.printLine(testString.Substring(1, testString.Length - 2))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 566: Line 793:


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>iex(1)> str = "abcdefg"
<syntaxhighlight lang="elixir">iex(1)> str = "abcdefg"
"abcdefg"
"abcdefg"
iex(2)> String.slice(str, 1..-1)
iex(2)> String.slice(str, 1..-1)
Line 573: Line 800:
"abcdef"
"abcdef"
iex(4)> String.slice(str, 1..-2)
iex(4)> String.slice(str, 1..-2)
"bcdef"</lang>
"bcdef"</syntaxhighlight>


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(let ((string "top and tail"))
<lang Emacs Lisp>
(substring string 1) ;=> "op and tail"
(progn
(setq string "top and tail")
(substring string 0 (1- (length string))) ;=> "top and tai"
(substring string 1 (1- (length string)))) ;=> "op and tai"</syntaxhighlight>
(insert (format "%s\n" string) )
(setq len (length string) )
(insert (format "%s\n" (substring string 1) ))
(insert (format "%s\n" (substring string 0 (1- len) )))
(insert (format "%s\n" (substring string 1 (1- len) ))))
</lang>
<b>Output:</b>
<pre>
top and tail
op and tail
top and tai
op and tai
</pre>


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>1> Str = "Hello".
<syntaxhighlight lang="erlang">1> Str = "Hello".
"Hello"
"Hello"
2> string:sub_string(Str, 2). % To strip the string from the right by 1
2> string:sub_string(Str, 2). % To strip the string from the right by 1
Line 601: Line 816:
"Hell"
"Hell"
4> string:sub_string(Str, 2, length(Str)-1). % To strip the string from both sides by 1
4> string:sub_string(Str, 2, length(Str)-1). % To strip the string from both sides by 1
"ell"</lang>
"ell"</syntaxhighlight>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>function strip_first(sequence s)
<syntaxhighlight lang="euphoria">function strip_first(sequence s)
return s[2..$]
return s[2..$]
end function
end function
Line 616: Line 831:
end function
end function


puts(1, strip_first("knight")) -- strip first character
puts(1, strip_first("knight")) -- strip first character
puts(1, strip_last("write")) -- strip last character
puts(1, strip_last("write")) -- strip last character
puts(1, strip_both("brooms")) -- strip both first and last characters</lang>
puts(1, strip_both("brooms")) -- strip both first and last characters</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>[<EntryPoint>]
<syntaxhighlight lang="fsharp">[<EntryPoint>]
let main args =
let main args =
let s = "一二三四五六七八九十"
let s = "一二三四五六七八九十"
Line 627: Line 842:
printfn "%A" (s.Substring(0, s.Length - 1))
printfn "%A" (s.Substring(0, s.Length - 1))
printfn "%A" (s.Substring(1, s.Length - 2))
printfn "%A" (s.Substring(1, s.Length - 2))
0</lang>
0</syntaxhighlight>
Output
Output
<pre>"二三四五六七八九十"
<pre>"二三四五六七八九十"
Line 634: Line 849:


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: io kernel sequences ;
<syntaxhighlight lang="factor">USING: io kernel sequences ;
"Rosetta code" [ rest ] [ but-last ] [ rest but-last ] tri
"Rosetta code" [ rest ] [ but-last ] [ rest but-last ] tri
[ print ] tri@</lang>
[ print ] tri@</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 647: Line 862:
In Forth, strings typically take up two cells on the stack, diagrammed ( c-addr u ), with C-ADDR the address of the string and U its length. Dropping leading and trailing characters then involves simple mathematical operations on the address or length, without mutating or copying the string.
In Forth, strings typically take up two cells on the stack, diagrammed ( c-addr u ), with C-ADDR the address of the string and U its length. Dropping leading and trailing characters then involves simple mathematical operations on the address or length, without mutating or copying the string.


<lang forth>: hello ( -- c-addr u )
<syntaxhighlight lang="forth">: hello ( -- c-addr u )
s" Hello" ;
s" Hello" ;


Line 654: Line 869:
hello 1- type \ => hell
hello 1- type \ => hell


hello 1 /string 1- type \ => ell</lang>
hello 1 /string 1- type \ => ell</syntaxhighlight>


This works for ASCII, and a slight variation (2 instead of 1 per character) will suffice for BIG5, GB2312, and like, but Unicode-general code can use +X/STRING and X\STRING- from Forth-200x's XCHAR wordset.
This works for ASCII, and a slight variation (2 instead of 1 per character) will suffice for BIG5, GB2312, and like, but Unicode-general code can use +X/STRING and X\STRING- from Forth-200x's XCHAR wordset.


=={{header|Fortran}}==
=={{header|Fortran}}==
<lang Fortran>program substring
<syntaxhighlight lang="fortran">program substring


character(len=5) :: string
character(len=5) :: string
Line 669: Line 884:
write (*,*) string(2:len(string)-1)
write (*,*) string(2:len(string)-1)


end program substring</lang>
end program substring</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Dim s As String = "panda"
Dim s As String = "panda"
Line 682: Line 897:
Print s2
Print s2
Print s3
Print s3
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 691: Line 906:
and
and
</pre>
</pre>


=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
void local fn DoIt
CFStringRef s = @"knights"
print s
CFStringRef s1 = mid(s, 1, len(s) - 1)
print s1
CFStringRef s2 = left(s, len(s) - 1)
print s2
CFStringRef s3 = mid(s, 1, len(s) - 2)
print s3
end fn

fn DoIt

HandleEvents
</syntaxhighlight>
{{output}}
<pre>
knights
nighs
knight
night
</pre>




=={{header|Go}}==
=={{header|Go}}==
Go strings are byte arrays that can hold whatever you want them to hold. Common contents are ASCII and UTF-8. You use different techniques depending on how you are interpreting the string. The utf8 package functions shown here allows efficient extraction of first and last runes without decoding the entire string.
Go strings are byte arrays that can hold whatever you want them to hold. Common contents are ASCII and UTF-8. You use different techniques depending on how you are interpreting the string. The utf8 package functions shown here allows efficient extraction of first and last runes without decoding the entire string.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 716: Line 959:
fmt.Println("Last rune removed: ", u[:len(u)-sizeLast])
fmt.Println("Last rune removed: ", u[:len(u)-sizeLast])
fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast])
fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast])
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 727: Line 970:
Last rune removed: Δημοτικ
Last rune removed: Δημοτικ
First and last removed: ημοτικ
First and last removed: ημοτικ
</pre>

=={{header|Golfscript}}==
When I tried using Unicode characters, the interpreter generated a mess, though ASCII works fine.
<syntaxhighlight lang="golfscript">
"Golfscript"(;n
"Golfscript");n
"Golfscript"(;);
</syntaxhighlight>
{{out}}
<pre>
olfscript
Golfscrip
olfscrip
</pre>
</pre>


=={{header|Groovy}}==
=={{header|Groovy}}==
Solution:
Solution:
<lang groovy>def top = { it.size() > 1 ? it[0..-2] : '' }
<syntaxhighlight lang="groovy">def top = { it.size() > 1 ? it[0..-2] : '' }
def tail = { it.size() > 1 ? it[1..-1] : '' }</lang>
def tail = { it.size() > 1 ? it[1..-1] : '' }</syntaxhighlight>


Test:
Test:
<lang groovy>def testVal = 'upraisers'
<syntaxhighlight lang="groovy">def testVal = 'upraisers'
println """
println """
original: ${testVal}
original: ${testVal}
Line 741: Line 998:
tail: ${tail(testVal)}
tail: ${tail(testVal)}
top&tail: ${tail(top(testVal))}
top&tail: ${tail(top(testVal))}
"""</lang>
"""</syntaxhighlight>


Output:
Output:
Line 750: Line 1,007:


=={{header|GW-BASIC}}==
=={{header|GW-BASIC}}==
<lang qbasic>10 A$="knight":B$="socks":C$="brooms"
<syntaxhighlight lang="qbasic">10 A$="knight":B$="socks":C$="brooms"
20 PRINT MID$(A$,2)
20 PRINT MID$(A$,2)
30 PRINT LEFT$(B$,LEN(B$)-1)
30 PRINT LEFT$(B$,LEN(B$)-1)
40 PRINT MID$(C$,2,LEN(C$)-2)</lang>
40 PRINT MID$(C$,2,LEN(C$)-2)</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang Haskell>-- We define the functions to return an empty string if the argument is too
<syntaxhighlight lang="haskell">-- We define the functions to return an empty string if the argument is too
-- short for the particular operation.
-- short for the particular operation.


Line 773: Line 1,030:
main = do
main = do
let s = "Some string."
let s = "Some string."
mapM_ (\f -> putStrLn . f $ s) [remFirst, remLast, remBoth]</lang>
mapM_ (\f -> putStrLn . f $ s) [remFirst, remLast, remBoth]</syntaxhighlight>


Alternative solution with builtin functions:
Alternative solution with builtin functions:
<lang Haskell>word = "knights"
<syntaxhighlight lang="haskell">word = "knights"


main = do
main = do
Line 793: Line 1,050:
-- You can combine functions using `.`,
-- You can combine functions using `.`,
-- which is pronounced "compose" or "of"
-- which is pronounced "compose" or "of"
middle = init . tail</lang>
middle = init . tail</syntaxhighlight>


In short:
In short:
<lang Haskell>main :: IO ()
<syntaxhighlight lang="haskell">main :: IO ()
main = mapM_ print $ [tail, init, init . tail] <*> ["knights"]</lang>
main = mapM_ print $ [tail, init, init . tail] <*> ["knights"]</syntaxhighlight>
{{Out}}
{{Out}}
<pre>"nights"
<pre>"nights"
Line 805: Line 1,062:
=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
The task is accomplished by sub-stringing.
The task is accomplished by sub-stringing.
<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
write(s := "knight"," --> ", s[2:0]) # drop 1st char
write(s := "knight"," --> ", s[2:0]) # drop 1st char
write(s := "sock"," --> ", s[1:-1]) # drop last
write(s := "sock"," --> ", s[1:-1]) # drop last
write(s := "brooms"," --> ", s[2:-1]) # drop both
write(s := "brooms"," --> ", s[2:-1]) # drop both
end</lang>
end</syntaxhighlight>


It could also be accomplished (less clearly) by assigning into the string as below. Very awkward for both front and back.
It could also be accomplished (less clearly) by assigning into the string as below. Very awkward for both front and back.
<lang Icon>write(s := "knight"," --> ", s[1] := "", s) # drop 1st char</lang>
<syntaxhighlight lang="icon">write(s := "knight"," --> ", s[1] := "", s) # drop 1st char</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
Line 818: Line 1,075:


'''Example use:'''<br>
'''Example use:'''<br>
<lang j> }. 'knight' NB. drop first item
<syntaxhighlight lang="j"> }. 'knight' NB. drop first item
night
night
}: 'socks' NB. drop last item
}: 'socks' NB. drop last item
sock
sock
}: }. 'brooms' NB. drop first and last items
}: }. 'brooms' NB. drop first and last items
room</lang>
room</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
I solve this problem two ways. First I use substring which is relatively fast for small strings, since it simply grabs the characters within a set of given bounds. The second uses regular expressions, which have a higher overhead for such short strings.
I solve this problem two ways. First I use substring which is relatively fast for small strings, since it simply grabs the characters within a set of given bounds. The second uses regular expressions, which have a higher overhead for such short strings, but work correctly with all Unicode code points, not just those in the Basic Multilingual Plane.


<lang Java>public class RM_chars {
<syntaxhighlight lang="java">public class RM_chars {
public static void main( String[] args ){
public static void main( String[] args ){
System.out.println( "knight".substring( 1 ) );
System.out.println( "knight".substring( 1 ) );
Line 841: Line 1,098:
// then do this using a regular expressions
// then do this using a regular expressions
}
}
}</lang>
}</syntaxhighlight>


Results:
Results:
Line 851: Line 1,108:
room</pre>
room</pre>


Nearly all current solutions for this task fail to work correctly: the task says "The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16." The code below works correctly with all Unicode characters, without using regular expressions as the above program does.
=={{header|JavaScript}}==


<syntaxhighlight lang="java">public class SubstringTopAndTail {
<lang javascript>alert("knight".slice(1)); // strip first character
public static void main( String[] args ){
var s = "\uD83D\uDC0Eabc\uD83D\uDC0E"; // Horse emoji, a, b, c, horse emoji: "🐎abc🐎"

var sizeOfFirstChar = Character.isSurrogate(s.charAt(0)) ? 2 : 1;
var sizeOfLastChar = Character.isSurrogate(s.charAt(s.length() - 1)) ? 2 : 1;

var removeFirst = s.substring(sizeOfFirstChar);
var removeLast = s.substring(0, s.length() - sizeOfLastChar);
var removeBoth = s.substring(sizeOfFirstChar, s.length() - sizeOfLastChar);

System.out.println(removeFirst);
System.out.println(removeLast);
System.out.println(removeBoth);
}
}</syntaxhighlight>

Results:
<pre>abc🐎
🐎abc
abc</pre>

=={{header|JavaScript}}==
<syntaxhighlight lang="javascript">alert("knight".slice(1)); // strip first character
alert("socks".slice(0, -1)); // strip last character
alert("socks".slice(0, -1)); // strip last character
alert("brooms".slice(1, -1)); // strip both first and last characters</lang>
alert("brooms".slice(1, -1)); // strip both first and last characters</syntaxhighlight>

=={{header|Joy}}==
<syntaxhighlight lang="joy">DEFINE
dropfirst == 1 drop;
droplast == dup size pred take.

"abcd" dropfirst.
"abcd" droplast.
"abcd" dropfirst droplast.</syntaxhighlight>
If a string is known to be non-empty, the <code>rest</code> operator could be used instead of <code>dropfirst</code>.
{{out}}
<pre>"bcd"
"abc"
"bc"</pre>


=={{header|jq}}==
=={{header|jq}}==
jq uses 0-based indexing, so [1:] yields all but the first character, it being understood that data strings in jq are JSON strings. [0:-1], which can be abbreviated to [:-1], yields all but the last character, and so on. Here are some examples:<lang jq>"一二三四五六七八九十"[1:]' => "二三四五六七八九十"
jq uses 0-based indexing, so [1:] yields all but the first character, it being understood that data strings in jq are JSON strings. [0:-1], which can be abbreviated to [:-1], yields all but the last character, and so on. Here are some examples:<syntaxhighlight lang="jq">"一二三四五六七八九十"[1:]' => "二三四五六七八九十"


"一二三四五六七八九十"[:-1]' => "一二三四五六七八九"
"一二三四五六七八九十"[:-1]' => "一二三四五六七八九"
Line 865: Line 1,159:


"a"[1:-1] # => ""
"a"[1:-1] # => ""
</syntaxhighlight>
</lang>
Recent versions of jq also have regular expression support, with named captures. This leads to many other possibilities, e.g.<lang jq>"abc" | capture( ".(?<monkey>.*)." ).monkey => "b"</lang>
Recent versions of jq also have regular expression support, with named captures. This leads to many other possibilities, e.g.<syntaxhighlight lang="jq">"abc" | capture( ".(?<monkey>.*)." ).monkey => "b"</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>julia> "My String"[2:end] # without first character
<syntaxhighlight lang="julia">julia> "My String"[2:end] # without first character
"y String"
"y String"


Line 876: Line 1,170:


julia> "My String"[2:end-1] # without first and last characters
julia> "My String"[2:end-1] # without first and last characters
"y Strin"</lang>
"y Strin"</syntaxhighlight>


=={{header|K}}==
=={{header|K}}==
K provides the system function <code>_di</code> to delete an element at
K provides the system function <code>_di</code> to delete an element at
a specified index. The following code is implemented using this feature.
a specified index. The following code is implemented using this feature.
<syntaxhighlight lang="k">
<lang K>
s: "1234567890"
s: "1234567890"
"1234567890"
"1234567890"
Line 890: Line 1,184:
(s _di -1+#s) _di 0 /String with both 1st and last character removed
(s _di -1+#s) _di 0 /String with both 1st and last character removed
"23456789"
"23456789"
</syntaxhighlight>
</lang>
Another way to implement without using the above system function:
Another way to implement without using the above system function:
<syntaxhighlight lang="k">
<lang K>
s: "1234567890"
s: "1234567890"
"1234567890"
"1234567890"
Line 901: Line 1,195:
1 - -1 _ s /Delete 1st and last character
1 - -1 _ s /Delete 1st and last character
"23456789"
"23456789"
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6
fun main(args: Array<String>) {
fun main(args: Array<String>) {
val s = "Rosetta"
val s = "Rosetta"
Line 910: Line 1,204:
println(s.dropLast(1))
println(s.dropLast(1))
println(s.drop(1).dropLast(1))
println(s.drop(1).dropLast(1))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 920: Line 1,214:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang lisp>
<syntaxhighlight lang="lisp">
{def R rosetta} -> rosetta
{def R rosetta} -> rosetta


Line 939: Line 1,233:
{W.rest {W.reverse {W.rest {W.reverse {J}}}}} -> トリン
{W.rest {W.reverse {W.rest {W.reverse {J}}}}} -> トリン


</syntaxhighlight>
</lang>


=={{header|Lasso}}==
=={{header|Lasso}}==


<lang Lasso>local(str = 'The quick grey rhino jumped over the lazy green fox.')
<syntaxhighlight lang="lasso">local(str = 'The quick grey rhino jumped over the lazy green fox.')


// String with first character removed
// String with first character removed
Line 952: Line 1,246:


// String with both the first and last characters removed
// String with both the first and last characters removed
string_remove(string_remove(#str,-startposition=#str->size,-endposition=#str->size),-startposition=1,-endposition=1)</lang>
string_remove(string_remove(#str,-startposition=#str->size,-endposition=#str->size),-startposition=1,-endposition=1)</syntaxhighlight>
{{out}}
{{out}}
<pre>he quick grey rhino jumped over the lazy green fox.
<pre>he quick grey rhino jumped over the lazy green fox.
Line 958: Line 1,252:
he quick grey rhino jumped over the lazy green fox</pre>
he quick grey rhino jumped over the lazy green fox</pre>


<lang Lasso>local(mystring = 'ÅÜÄÖカ')
<syntaxhighlight lang="lasso">local(mystring = 'ÅÜÄÖカ')


#mystring -> remove(1,1)
#mystring -> remove(1,1)
Line 967: Line 1,261:
'<br />'
'<br />'
#mystring -> remove(1,1)& -> remove(#mystring -> size,1)
#mystring -> remove(1,1)& -> remove(#mystring -> size,1)
#mystring</lang>
#mystring</syntaxhighlight>
-> ÜÄÖカ
-> ÜÄÖカ


Line 973: Line 1,267:


Ä =={{header|Lasso}}==
Ä =={{header|Lasso}}==
<lang Lasso>local(str = 'The quick grey rhino jumped over the lazy green fox.')
<syntaxhighlight lang="lasso">local(str = 'The quick grey rhino jumped over the lazy green fox.')


// String with first character removed
// String with first character removed
Line 985: Line 1,279:
// String with both the first and last characters removed
// String with both the first and last characters removed
string_remove(string_remove(#str,-startposition=#str->size,-endposition=#str->size),-startposition=1,-endposition=1)
string_remove(string_remove(#str,-startposition=#str->size,-endposition=#str->size),-startposition=1,-endposition=1)
// > he quick grey rhino jumped over the lazy green fox</lang>
// > he quick grey rhino jumped over the lazy green fox</syntaxhighlight>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>string$ = "Rosetta Code"
<syntaxhighlight lang="lb">string$ = "Rosetta Code"
Print Mid$(string$, 2)
Print Mid$(string$, 2)
Print Left$(string$, (Len(string$) - 1))
Print Left$(string$, (Len(string$) - 1))
Print Mid$(string$, 2, (Len(string$) - 2))</lang>
Print Mid$(string$, 2, (Len(string$) - 2))</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
<lang LiveCode>put "pple" into x
<syntaxhighlight lang="livecode">put "pple" into x
answer char 2 to len(x) of x // pple
answer char 2 to len(x) of x // pple
answer char 1 to -2 of x // ppl
answer char 1 to -2 of x // ppl
answer char 2 to -2 of x // ppl</lang>
answer char 2 to -2 of x // ppl</syntaxhighlight>


=={{header|Locomotive Basic}}==
=={{header|Locomotive Basic}}==


<lang locobasic>10 a$="knight":b$="socks":c$="brooms"
<syntaxhighlight lang="locobasic">10 a$="knight":b$="socks":c$="brooms"
20 PRINT MID$(a$,2)
20 PRINT MID$(a$,2)
30 PRINT LEFT$(b$,LEN(b$)-1)
30 PRINT LEFT$(b$,LEN(b$)-1)
40 PRINT MID$(c$,2,LEN(c$)-2)</lang>
40 PRINT MID$(c$,2,LEN(c$)-2)</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>make "s "|My string|
<syntaxhighlight lang="logo">make "s "|My string|
print butfirst :s
print butfirst :s
print butlast :s
print butlast :s
print butfirst butlast :s</lang>
print butfirst butlast :s</syntaxhighlight>


=={{header|Logtalk}}==
=={{header|Logtalk}}==
Using atoms for representing strings:
Using atoms for representing strings:
<lang logtalk>
<syntaxhighlight lang="logtalk">
:- object(top_and_tail).
:- object(top_and_tail).


Line 1,027: Line 1,321:


:- end_object.
:- end_object.
</syntaxhighlight>
</lang>
Sample output:
Sample output:
<lang text>
<syntaxhighlight lang="text">
| ?- top_and_tail::test('Rosetta').
| ?- top_and_tail::test('Rosetta').
String with first character cut: osetta
String with first character cut: osetta
Line 1,035: Line 1,329:
String with first and last characters cut: osett
String with first and last characters cut: osett
yes
yes
</syntaxhighlight>
</lang>


=={{header|Lua}}==
=={{header|Lua}}==


<lang lua>print (string.sub("knights",2)) -- remove the first character
<syntaxhighlight lang="lua">print (string.sub("knights",2)) -- remove the first character
print (string.sub("knights",1,-2)) -- remove the last character
print (string.sub("knights",1,-2)) -- remove the last character
print (string.sub("knights",2,-2)) -- remove the first and last characters</lang>
print (string.sub("knights",2,-2)) -- remove the first and last characters</syntaxhighlight>


=={{header|Maple}}==
=={{header|Maple}}==
There are several ways to do this. The first is, I think, the simplest.
There are several ways to do this. The first is, I think, the simplest.
<lang Maple>> s := "some string":
<syntaxhighlight lang="maple">> s := "some string":
> s[2..-1];
> s[2..-1];
"ome string"
"ome string"
Line 1,053: Line 1,347:


> s[2..-2];
> s[2..-2];
"ome strin"</lang>
"ome strin"</syntaxhighlight>
The same functionality exists in the form of a procedure:
The same functionality exists in the form of a procedure:
<lang Maple>> substring( s, 2 .. -1 );
<syntaxhighlight lang="maple">> substring( s, 2 .. -1 );
"ome string"
"ome string"


Line 1,062: Line 1,356:


> substring( s, 2 .. -2 );
> substring( s, 2 .. -2 );
"ome strin"</lang>
"ome strin"</syntaxhighlight>
Furthermore, there is a slightly different version in the "StringTools" package:
Furthermore, there is a slightly different version in the "StringTools" package:
<lang Maple>> use StringTools in
<syntaxhighlight lang="maple">> use StringTools in
> SubString( s, 2 .. -1 );
> SubString( s, 2 .. -1 );
> SubString( s, 1 .. -1 );
> SubString( s, 1 .. -1 );
Line 1,073: Line 1,367:
"some string"
"some string"


"ome strin"</lang>
"ome strin"</syntaxhighlight>
(The difference between "substring" and "StringTools:-SubString" lies in how each treats a name as input; the former returns a name, while the latter returns a string.)
(The difference between "substring" and "StringTools:-SubString" lies in how each treats a name as input; the former returns a name, while the latter returns a string.)


=={{header|Mathematica}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">StringDrop["input string",1]

<lang Mathematica>StringDrop["input string",1]
StringDrop["input string",-1]
StringDrop["input string",-1]
StringTake["input string",{2,-2}]
StringTake["input string",{2,-2}]
</syntaxhighlight>
</lang>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==


The following case will not handle UTF-8. However, Matlab supports conversion of utf-8 to utf-16 using native2unicode().
The following case will not handle UTF-8. However, Matlab supports conversion of utf-8 to utf-16 using native2unicode().
<syntaxhighlight lang="matlab">
<lang MATLAB>
% String with first character removed
% String with first character removed
str(2:end)
str(2:end)
% String with last character removed
% String with last character removed
str(1:end-1)
str(1:end-1)
% String with both the first and last characters removed
% String with both the first and last characters removed
str(2:end-1)
str(2:end-1)
</syntaxhighlight>
</lang>


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>test = "This thing"
<syntaxhighlight lang="miniscript">test = "This thing"
print test[1:]
print test[1:]
print test[:-1]
print test[:-1]
print test[1:-1]
print test[1:-1]
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,107: Line 1,400:
his thin
his thin
</pre>
</pre>

=={{header|MIPS Assembly}}==
Thanks to [https://www.chibialiens.com/mips/ Chibialiens] for the header/footer, font, and print routines.
<syntaxhighlight lang="mips">.include "\SrcAll\Header.asm"
.include "\SrcAll\BasicMacros.asm"
.include "\SrcALL\AdvancedMacros.asm"
.include "\SrcALL\MemoryMap.asm"

; .definelabel UserRam,0xA0010000 (this is defined in the header)

CursorX equ 0x100 ;offset from label UserRam
CursorY equ 0x101 ;offset from label UserRam

main:
jal Cls
nop
la a0,MyString
la a1,UserRam+0x1000
push a0
push a1
jal strcpy
addiu a0,1 ;branch delay slot - increment base address prior to branching
pop a0 ;deliberately pop in the "wrong order"
pop a1 ;because printString uses $a0
jal PrintString
nop
jal NewLine
nop
la a0,MyString
la a1,UserRam+0x1000
push a0
push a1
jal strcpy
nop ;branch delay slot
;after a strcpy, a0/a1 both point to the null terminator
subiu a1,1
move t0,zero
sb t0,(a1)
.ifdef buildPSX
nop ;load delay slot
.endif
pop a0
pop a1
jal PrintString
nop
jal NewLine
nop
la a0,MyString
la a1,UserRam+0x1000
push a0
push a1
jal strcpy
addiu a0,1 ;branch delay slot
;after a strcpy, a0/a1 both point to the null terminator
subiu a1,1
move t0,zero
sb t0,(a1)
.ifdef buildPSX
nop ;load delay slot
.endif
pop a0
pop a1
jal PrintString
nop
jal NewLine
nop
halt:
nop
j halt
nop
MyString:
.ascii "Hello World"
.byte 0
.align 4
MyFont:

.ifdef buildn64
.incbin "\ResN64\ChibiAkumas.fnt"
.endif
.ifdef buildPSX
.incbin "\ResPSX\ChibiAkumas.fnt"
.endif

.include "\SrcALL\graphics.asm"
.include "\SrcAll\monitor.asm"
.include "\SrcALL\Multiplatform_Math_Integer.asm"
.include "\SrcALL\BasicFunctions_v2.asm"
.include "\SrcN64\Footer.asm"</syntaxhighlight>
{{out}}
<pre>ello World
Hello Worl
ello Worl</pre>
[https://ibb.co/CHwTrMb Screenshot of PlayStation 1 Emulator]


=={{header|Neko}}==
=={{header|Neko}}==
Line 1,112: Line 1,513:


'''$ssub''' ''sub-string'' takes string, position (zero-relative), length arguments.
'''$ssub''' ''sub-string'' takes string, position (zero-relative), length arguments.
<syntaxhighlight lang="actionscript">/**
<lang ActionScript>/**
Subtring/Top-Tail in Neko
Subtring/Top-Tail in Neko
*/
*/
Line 1,122: Line 1,523:
$print($ssub(data, 1, len - 1), "\n")
$print($ssub(data, 1, len - 1), "\n")
$print($ssub(data, 0, len - 1), "\n")
$print($ssub(data, 0, len - 1), "\n")
$print($ssub(data, 1, len - 2), "\n")</lang>
$print($ssub(data, 1, len - 2), "\n")</syntaxhighlight>


{{out}}
{{out}}
Line 1,133: Line 1,534:


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>using System;
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using System.Console;


Line 1,147: Line 1,548:
WriteLine($"$str -> $beg -> $end -> $both");
WriteLine($"$str -> $beg -> $end -> $both");
}
}
}</lang>
}</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang netrexx>/**********************************************************************
<syntaxhighlight lang="netrexx">/**********************************************************************
* 02.08.2013 Walter Pachl translated from REXX
* 02.08.2013 Walter Pachl translated from REXX
**********************************************************************/
**********************************************************************/
Line 1,161: Line 1,562:
End
End
If l>=2 Then
If l>=2 Then
Say 'string first & last character removed =' z.substr(2,l-2)</lang>
Say 'string first & last character removed =' z.substr(2,l-2)</syntaxhighlight>


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP>(let (str "rosetta")
<syntaxhighlight lang="newlisp">(let (str "rosetta")
;; strip first char
;; strip first char
(println (1 str))
(println (1 str))
Line 1,170: Line 1,571:
(println (0 -1 str))
(println (0 -1 str))
;; strip both first and last characters
;; strip both first and last characters
(println (1 -1 str)))</lang>
(println (1 -1 str)))</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import unicode
<syntaxhighlight lang="nim">import unicode


let s = "Hänsel ««: 10,00€"
let s = "Hänsel ««: 10,00€"
echo "Original: ", s
echo(s.runeSubStr(1))
echo(s.runeSubStr(0, -1))
echo "With first character removed: ", s.runeSubStr(1)
echo(s.runeSubStr(1, -1))
echo "With last character removed: ", s.runeSubStr(0, s.runeLen - 1)
echo "With first and last characters removed: ", s.runeSubStr(1, s.runeLen - 2)
# using the runes type and slices
# Using the runes type and slices
let r = s.toRunes
let r = s.toRunes
echo "With first and last characters removed (other way): ", r[1 .. ^2]</syntaxhighlight>
echo(r[1 .. ^2])</lang>
{{out}}
{{out}}
<pre>änsel ««: 10,00€
<pre>Original: Hänsel ««: 10,00€
Hänsel ««: 10,00
With first character removed: änsel ««: 10,00€
änsel ««: 10,00
With last character removed: Hänsel ««: 10,00
änsel ««: 10,00</pre>
With first and last characters removed: änsel ««: 10,00
With first and last characters removed (other way): änsel ««: 10,00</pre>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
bundle Default {
bundle Default {
class TopTail {
class TopTail {
Line 1,200: Line 1,603:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==


<lang ocaml>let strip_first_char str =
<syntaxhighlight lang="ocaml">let strip_first_char str =
if str = "" then "" else
if str = "" then "" else
String.sub str 1 ((String.length str) - 1)
String.sub str 1 ((String.length str) - 1)
Line 1,221: Line 1,624:
print_endline (strip_last_char "socks");
print_endline (strip_last_char "socks");
print_endline (strip_both_chars "brooms");
print_endline (strip_both_chars "brooms");
;;</lang>
;;</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>: topAndTail(s)
<syntaxhighlight lang="oforth">: topAndTail(s)
s right(s size 1-) println
s right(s size 1-) println
s left(s size 1-) println
s left(s size 1-) println
s extract(2, s size 1- ) println ;</lang>
s extract(2, s size 1- ) println ;</syntaxhighlight>


{{out}}
{{out}}
Line 1,239: Line 1,642:


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>df(s)=concat(vecextract(Vec(s),1<<#s-2));
<syntaxhighlight lang="parigp">df(s)=concat(vecextract(Vec(s),1<<#s-2));
dl(s)=concat(vecextract(Vec(s),1<<(#s-1)-1));
dl(s)=concat(vecextract(Vec(s),1<<(#s-1)-1));
db(s)=concat(vecextract(Vec(s),1<<(#s-1)-2));</lang>
db(s)=concat(vecextract(Vec(s),1<<(#s-1)-2));</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
See [[Substring/Top_and_tail#Delphi | Delphi]]
''See also [[#Delphi|Delphi]]''
{{works with|Extended Pascal}}
<syntaxhighlight lang="pascal">program topAndTail(output);
var
line: string(20);
begin
line := 'ABCDEF';
if length(line) > 1 then
begin
{ string with first character removed }
writeLn(subStr(line, 2));
{ index range expression: only possible for strings }
{ _not_ designated `bindable` [e.g. `bindable string(20)`] }
writeLn(line[2..length(line)]);
{ string with last character removed }
writeLn(subStr(line, 1, length(line) - 1));
{ only legal with non-bindable strings: }
writeLn(line[1..length(line)-1])
end;
{ string with both the first and last characters removed }
if length(line) > 2 then
begin
writeLn(subStr(line, 2, length(line) - 2));
{ only for non-bindable strings: }
writeLn(line[2..length(line)-1])
end
end.</syntaxhighlight>It is imperative that <tt>firstCharacterIndex + substringLength</tt> specified to <tt>subStr(source, firstCharacterIndex, substringLength)</tt> must be valid index in <tt>source</tt>. Therefore you need to perform checks beforehand.


=={{header|Perl}}==
=={{header|Perl}}==


<lang perl>print substr("knight",1), "\n"; # strip first character
<syntaxhighlight lang="perl">print substr("knight",1), "\n"; # strip first character
print substr("socks", 0, -1), "\n"; # strip last character
print substr("socks", 0, -1), "\n"; # strip last character
print substr("brooms", 1, -1), "\n"; # strip both first and last characters</lang>
print substr("brooms", 1, -1), "\n"; # strip both first and last characters</syntaxhighlight>


In perl, we can also remove the last character from a string variable with the chop function:
In perl, we can also remove the last character from a string variable with the chop function:


<lang perl>$string = 'ouch';
<syntaxhighlight lang="perl">$string = 'ouch';
$bits = chop($string); # The last letter is returned by the chop function
$bits = chop($string); # The last letter is returned by the chop function
print $bits; # h
print $bits; # h
print $string; # ouc # See we really did chop the last letter off</lang>
print $string; # ouc # See we really did chop the last letter off</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/basics}}
<lang Phix>constant s = "(test)"
<!--<syntaxhighlight lang="phix">-->
?s[2..-1]
<span style="color: #008080;">constant</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"(test)"</span>
?s[1..-2]
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">..-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
?s[2..-2]</lang>
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">..-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]</span>
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,270: Line 1,706:
"test"
"test"
</pre>
</pre>

=={{header|Phixmonti}}==
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt

"(test)"
dup 1 del ?
dup -1 del ?
dup 1 del -1 del ?</syntaxhighlight>
Or...
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt

"(test)"
len 1 - 2 swap slice ?
len 1 - 1 swap slice ?
len 2 - 2 swap slice ?</syntaxhighlight>


=={{header|PHP}}==
=={{header|PHP}}==


<lang php><?php
<syntaxhighlight lang="php"><?php
echo substr("knight", 1), "\n"; // strip first character
echo substr("knight", 1), "\n"; // strip first character
echo substr("socks", 0, -1), "\n"; // strip last character
echo substr("socks", 0, -1), "\n"; // strip last character
echo substr("brooms", 1, -1), "\n"; // strip both first and last characters
echo substr("brooms", 1, -1), "\n"; // strip both first and last characters
?></lang>
?></syntaxhighlight>

=={{header|Picat}}==
===Functions===
<syntaxhighlight lang="picat">go =>
test("upraisers"),
test("Δημοτική"),
nl.

test(S) =>
println(s=S),
println(butfirst=S.slice(2)),
println(butfirst=S.tail),
println(butfirst=S[2..S.len]),
println(butlast=S.but_last()),
println(butfirst_butlast=S.tail.but_last),
println(butfirst_butlast=slice(S,2,S.length-1)),
println(butfirst_butlast=[S[I] : I in 2..S.length-1]),
println(butfirst_butlast=S[2..S.length-1]),
nl.

but_last(S) = S.slice(1,S.length-1).</syntaxhighlight>

{{out}}
<pre>s = upraisers
butfirst = praisers
butfirst = praisers
butfirst = praisers
butlast = upraiser
butfirst_butlast = praiser
butfirst_butlast = praiser
butfirst_butlast = praiser
butfirst_butlast = praiser

s = Δημοτική
butfirst = ημοτική
butfirst = ημοτική
butfirst = ημοτική
butlast = Δημοτικ
butfirst_butlast = ημοτικ
butfirst_butlast = ημοτικ
butfirst_butlast = ημοτικ
butfirst_butlast = ημοτικ</pre>

===Using append/3===
{{trans|Prolog}}
<syntaxhighlight lang="picat">go2 =>
test2("upraisers"),
nl,
test2("Δημοτική"),
nl.

test2(L) :-
L = [_|L1],
remove_last(L, L2),
remove_last(L1, L3),
writef("Original string : %s\n", L),
writef("Without first char : %s\n", L1),
writef("Without last char : %s\n", L2),
writef("Without first/last chars : %s\n", L3).
remove_last(L, LR) :-
append(LR, [_], L).</syntaxhighlight>

{{out}}
<pre>Original string : upraisers
Without first char : praisers
Without last char : upraiser
Without first/last chars : praiser

Original string : Δημοτική
Without first char : ημοτική
Without last char : Δημοτικ
Without first/last chars : ημοτικ</pre>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>: (pack (cdr (chop "knight"))) # Remove first character
<syntaxhighlight lang="picolisp">: (pack (cdr (chop "knight"))) # Remove first character
-> "night"
-> "night"


Line 1,287: Line 1,813:


: (pack (cddr (rot (chop "brooms")))) # Remove first and last characters
: (pack (cddr (rot (chop "brooms")))) # Remove first and last characters
-> "room"</lang>
-> "room"</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
declare s character (100) varying;
declare s character (100) varying;
s = 'now is the time to come to the aid of the party';
s = 'now is the time to come to the aid of the party';
Line 1,298: Line 1,824:
put skip list ('One character from each end removed=' ||
put skip list ('One character from each end removed=' ||
substr(s, 2, length(s)-2) );
substr(s, 2, length(s)-2) );
</syntaxhighlight>
</lang>
OUTPUT:
OUTPUT:
<pre>
<pre>
Line 1,304: Line 1,830:
Last character removed=now is the time to come to the aid of the part
Last character removed=now is the time to come to the aid of the part
One character from each end removed=ow is the time to come to the aid of the part
One character from each end removed=ow is the time to come to the aid of the part
</pre>

=={{header|Plain English}}==
<syntaxhighlight lang="plainenglish">To run:
Start up.
Demonstrate removing the first and last characters from "Rosetta Code".
Wait for the escape key.
Shut down.

To demonstrate removing the first and last characters from a string:
Slap a substring on the string.
Add 1 to the substring's first.
Write the substring on the console.
Subtract 1 from the substring's first.
Subtract 1 from the substring's last.
Write the substring on the console.
Add 1 to the substring's first.
Write the substring on the console.</syntaxhighlight>
{{out}}
<pre>
osetta Code
Rosetta Cod
osetta Cod
</pre>
</pre>


Line 1,309: Line 1,858:
{{works with|PowerShell|4.0}}
{{works with|PowerShell|4.0}}
===First method===
===First method===
<syntaxhighlight lang="powershell">
<lang PowerShell>
$string = "top and tail"
$string = "top and tail"
$string
$string
Line 1,315: Line 1,864:
$string.Substring(0, $string.Length - 1)
$string.Substring(0, $string.Length - 1)
$string.Substring(1, $string.Length - 2)
$string.Substring(1, $string.Length - 2)
</syntaxhighlight>
</lang>
===Second method===
===Second method===
<syntaxhighlight lang="powershell">
<lang PowerShell>
$string = "top and tail"
$string = "top and tail"
$string
$string
Line 1,323: Line 1,872:
$string[0..($string.Length - 2)] -join ""
$string[0..($string.Length - 2)] -join ""
$string[1..($string.Length - 2)] -join ""
$string[1..($string.Length - 2)] -join ""
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 1,335: Line 1,884:
Works with SWI-Prolog.
Works with SWI-Prolog.


<lang Prolog>remove_first_last_chars :-
<syntaxhighlight lang="prolog">remove_first_last_chars :-
L = "Rosetta",
L = "Rosetta",
L = [_|L1],
L = [_|L1],
remove_last(L, L2),
remove_last(L, L2),
remove_last(L1, L3),
remove_last(L1, L3),
writef('Original string : %s\n', [L]),
writef('Original string : %s\n', [L]),
writef('Without first char : %s\n', [L1]),
writef('Without first char : %s\n', [L1]),
writef('Without last char : %s\n', [L2]),
writef('Without last char : %s\n', [L2]),
writef('Without first/last chars : %s\n', [L3]).
writef('Without first/last chars : %s\n', [L3]).


remove_last(L, LR) :-
remove_last(L, LR) :-
append(LR, [_], L).</lang>
append(LR, [_], L).</syntaxhighlight>
Output :
Output :
<pre> ?- remove_first_last_chars.
<pre> ?- remove_first_last_chars.
Line 1,357: Line 1,906:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>If OpenConsole()
<syntaxhighlight lang="purebasic">If OpenConsole()
PrintN(Right("knight", Len("knight") - 1)) ;strip the first letter
PrintN(Right("knight", Len("knight") - 1)) ;strip the first letter
PrintN(Left("socks", Len("socks")- 1)) ;strip the last letter
PrintN(Left("socks", Len("socks")- 1)) ;strip the last letter
Line 1,364: Line 1,913:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>
Sample output:
Sample output:
<pre>night
<pre>night
Line 1,372: Line 1,921:
=={{header|Python}}==
=={{header|Python}}==


<lang python>print "knight"[1:] # strip first character
<syntaxhighlight lang="python">print "knight"[1:] # strip first character
print "socks"[:-1] # strip last character
print "socks"[:-1] # strip last character
print "brooms"[1:-1] # strip both first and last characters</lang>
print "brooms"[1:-1] # strip both first and last characters</syntaxhighlight>




Or, composing atomic functional expressions for these slices:
Or, composing atomic functional expressions for these slices:
<lang python>from functools import (reduce)
<syntaxhighlight lang="python">from functools import (reduce)




Line 1,432: Line 1,981:


if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>['nights', 'knight', 'night']
<pre>['nights', 'knight', 'night']
['ocks', 'sock', 'ock']
['ocks', 'sock', 'ock']
['rooms', 'broom', 'room']</pre>
['rooms', 'broom', 'room']</pre>

=={{header|Quackery}}==

As a dialogue in the Quackery shell.

<pre>/O> $ "callipygian"
... say "original string: "
... dup echo$ cr
... say "without head: "
... dup behead drop echo$ cr
... say "without tail: "
... -1 split drop dup echo$ cr
... say "topped and tailed: "
... behead drop echo$ cr
...
original string: callipygian
without head: allipygian
without tail: callipygia
topped and tailed: allipygia
</pre>


=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 1,448: Line 2,017:
(substring str 0 (sub1 (string-length str)))
(substring str 0 (sub1 (string-length str)))
(substring str 1 (sub1 (string-length str)))
(substring str 1 (sub1 (string-length str)))
</syntaxhighlight>
</lang>


Output:
Output:
Line 1,461: Line 2,030:
(formerly Perl 6)
(formerly Perl 6)


Raku provides both functional and method forms of substr. Note that, unlike in Perl 5, offsets from the end do not use negative numbers, but instead require a function expressing the negative offset relative to the length parameter, which is supplied by the operator. The form <tt>*-1</tt> is just a simple way to write such a function.
Raku provides both functional and method forms of substr. Note that, unlike in Perl 5, offsets from the end do not use negative numbers, but instead require a function expressing the negative offset relative to the length parameter, which is supplied by the operator. The form <tt>*-1</tt> is just a simple way to write such a function.


We use musical sharps and flats to illustrate that Raku is comfortable with characters from any Unicode plane.
We use musical sharps and flats to illustrate that Raku is comfortable with characters from any Unicode plane.


<lang perl6>my $s = '𝄪♯♮♭𝄫';
<syntaxhighlight lang="raku" line>my $s = '𝄪♯♮♭𝄫';


print qq:to/END/;
print qq:to/END/;
Line 1,483: Line 2,052:
{ substr($s, 1, *-1) }
{ substr($s, 1, *-1) }
{ $s.substr(1, *-1) }
{ $s.substr(1, *-1) }
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>Original:
<pre>Original:
Line 1,502: Line 2,071:


=={{header|Raven}}==
=={{header|Raven}}==
<lang Raven>define println use $s
<syntaxhighlight lang="raven">define println use $s
$s print "\n" print
$s print "\n" print


Line 1,516: Line 2,085:
$str offTheTop println
$str offTheTop println
$str offTheTail println
$str offTheTail println
$str offTheTop offTheTail println</lang>
$str offTheTop offTheTail println</syntaxhighlight>
{{out}}
{{out}}
<pre>123456789
<pre>123456789
Line 1,525: Line 2,094:
===error prone===
===error prone===
This REXX version is error prone in that if the string is less than two characters, then the &nbsp; '''left''' &nbsp; and/or &nbsp; '''substr''' &nbsp; BIFs will fail &nbsp; (because of an invalid length specified).
This REXX version is error prone in that if the string is less than two characters, then the &nbsp; '''left''' &nbsp; and/or &nbsp; '''substr''' &nbsp; BIFs will fail &nbsp; (because of an invalid length specified).
<lang rexx>/*REXX program demonstrates removal of 1st/last/1st-and-last characters from a string.*/
<syntaxhighlight lang="rexx">/*REXX program demonstrates removal of 1st/last/1st-and-last characters from a string.*/
@ = 'abcdefghijk'
@ = 'abcdefghijk'
say ' the original string =' @
say ' the original string =' @
Line 1,535: Line 2,104:
║ However, the original string may be null or exactly one byte in length which ║
║ However, the original string may be null or exactly one byte in length which ║
║ will cause the BIFs to fail because of either zero or a negative length. ║
║ will cause the BIFs to fail because of either zero or a negative length. ║
╚═══════════════════════════════════════════════════════════════════════════════╝ */</lang>
╚═══════════════════════════════════════════════════════════════════════════════╝ */</syntaxhighlight>
'''output'''
'''output'''
<pre>
<pre>
Line 1,546: Line 2,115:
===robust version===
===robust version===
This REXX version correctly handles a string of zero (null) or one byte.
This REXX version correctly handles a string of zero (null) or one byte.
<lang rexx>/*REXX program demonstrates removal of 1st/last/1st-and-last characters from a string.*/
<syntaxhighlight lang="rexx">/*REXX program demonstrates removal of 1st/last/1st-and-last characters from a string.*/
@ = 'abcdefghijk'
@ = 'abcdefghijk'
say ' the original string =' @
say ' the original string =' @
Line 1,560: Line 2,129:
say 'string first character removed =' substr(@, 2)
say 'string first character removed =' substr(@, 2)
say 'string last character removed =' left(@, max(0, L-1) )
say 'string last character removed =' left(@, max(0, L-1) )
say 'string first & last character removed =' substr(@, 2, max(0, L-2) )</lang>
say 'string first & last character removed =' substr(@, 2, max(0, L-2) )</syntaxhighlight>
'''output''' &nbsp; is the same as the 1<sup>st</sup> REXX version.
'''output''' &nbsp; is the same as the 1<sup>st</sup> REXX version.


===faster version===
===faster version===
This REXX version is faster &nbsp; (uses &nbsp; '''parse''' &nbsp; instead of multiple BIFs).
This REXX version is faster &nbsp; (uses &nbsp; '''parse''' &nbsp; instead of multiple BIFs).
<lang rexx>/*REXX program demonstrates removal of 1st/last/1st-and-last characters from a string.*/
<syntaxhighlight lang="rexx">/*REXX program demonstrates removal of 1st/last/1st-and-last characters from a string.*/
@ = 'abcdefghijk'
@ = 'abcdefghijk'
say ' the original string =' @
say ' the original string =' @
Line 1,579: Line 2,148:
parse var @ 2 z +(n)
parse var @ 2 z +(n)
if n==0 then z= /*handle special case of a length of 2.*/
if n==0 then z= /*handle special case of a length of 2.*/
say 'string first & last character removed =' z /*stick a fork in it, we're all done. */</lang>
say 'string first & last character removed =' z /*stick a fork in it, we're all done. */</syntaxhighlight>
'''output''' &nbsp; is the same as the 1<sup>st</sup> REXX version. <br><br>
'''output''' &nbsp; is the same as the 1<sup>st</sup> REXX version. <br><br>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
aString = "1Welcome to the Ring Programming Language2"
aString = "1Welcome to the Ring Programming Language2"
see substr(aString,2,len(aString)-1) + nl +
see substr(aString,2,len(aString)-1) + nl +
substr(aString,1,len(aString)-1) + nl +
substr(aString,1,len(aString)-1) + nl +
substr(aString,2,len(aString)-2) + nl
substr(aString,2,len(aString)-2) + nl
</syntaxhighlight>
</lang>

=={{header|RPL}}==
Basic RPL:
"Knight" 2 OVER SIZE SUB
"Socks" 1 OVER SIZE 1 - SUB
"Brooms" 2 OVER SIZE 1 - SUB
From HP-48 versions, one can also do this way:
"Knight" TAIL
"Socks" REVLIST TAIL REVLIST
"Brooms" TAIL REVLIST TAIL REVLIST
{{out}}
<pre>
3: night
2: Sock
1: room
</pre>


=={{header|Ruby}}==
=={{header|Ruby}}==


<lang ruby>puts "knight"[1..-1] # strip first character
<syntaxhighlight lang="ruby">puts "knight"[1..-1] # strip first character
puts "socks"[0..-2] # strip last character
puts "socks"[0..-2] # strip last character
puts "socks".chop # alternate way to strip last character
puts "socks".chop # alternate way to strip last character
puts "brooms"[1..-2] # strip both first and last characters
puts "brooms"[1..-2] # strip both first and last characters
puts "与今令"[1..-2] # => 今</lang>
puts "与今令"[1..-2] # => 今</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>s$ = "Run BASIC"
<syntaxhighlight lang="runbasic">s$ = "Run BASIC"
print mid$(s$,2) 'strip first
print mid$(s$,2) 'strip first
print left$(s$,len(s$) -1) 'strip last
print left$(s$,len(s$) -1) 'strip last
print mid$(s$,2,len(s$) -2) 'strip first and last</lang>
print mid$(s$,2,len(s$) -2) 'strip first and last</syntaxhighlight>

=={{header|Rust}}==
One possibility is to modify the owned string representation:
<syntaxhighlight lang="rust">fn main() {
let s = String::from("žluťoučký kůň");

let mut modified = s.clone();
modified.remove(0);
println!("{}", modified);

let mut modified = s.clone();
modified.pop();
println!("{}", modified);

let mut modified = s;
modified.remove(0);
modified.pop();
println!("{}", modified);
}</syntaxhighlight>

Another possibility is to cut a string slice (moreover, this version assumes
nothing about the string length):
<syntaxhighlight lang="rust">fn main() {
let s = "žluťoučký kůň";

println!(
"{}",
s.char_indices()
.nth(1)
.map(|(i, _)| &s[i..])
.unwrap_or_default()
);

println!(
"{}",
s.char_indices()
.nth_back(0)
.map(|(i, _)| &s[..i])
.unwrap_or_default()
);

println!(
"{}",
s.char_indices()
.nth(1)
.and_then(|(i, _)| s.char_indices().nth_back(0).map(|(j, _)| i..j))
.map(|range| &s[range])
.unwrap_or_default()
);
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}
{{libheader|Scala}}
<lang scala>println("knight".tail) // strip first character
<syntaxhighlight lang="scala">println("knight".tail) // strip first character
println("socks".init) // strip last character
println("socks".init) // strip last character
println("brooms".tail.init) // strip both first and last characters</lang>
println("brooms".tail.init) // strip both first and last characters</syntaxhighlight>

=={{header|Scheme}}==
<syntaxhighlight lang="scheme">(define (string-top s)
(if (string=? s "") s (substring s 0 (- (string-length s) 1))))

(define (string-tail s)
(if (string=? s "") s (substring s 1 (string-length s))))

(define (string-top-tail s)
(string-tail (string-top s)))</syntaxhighlight>

=={{header|sed}}==
Remove the first character:
<syntaxhighlight lang="sed">s/.//</syntaxhighlight>
Remove the last character:
<syntaxhighlight lang="sed">s/.$//</syntaxhighlight>
Remove the first and the last character in one step (a bit more complex, to correctly handle single-character strings):
<syntaxhighlight lang="sed">s/.\(\(.*\).\)\{0,1\}/\2/</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const proc: main is func
const proc: main is func
Line 1,621: Line 2,274:
writeln("Without last: " <& stri[.. pred(length(stri))]);
writeln("Without last: " <& stri[.. pred(length(stri))]);
writeln("Without both: " <& stri[2 .. pred(length(stri))]);
writeln("Without both: " <& stri[2 .. pred(length(stri))]);
end func;</lang>
end func;</syntaxhighlight>


Output:
Output:
Line 1,632: Line 2,285:


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<lang sensetalk>
<syntaxhighlight lang="sensetalk">
set message to peaceSymbol & "Peace!"
set message to peaceSymbol & "Peace!"
put message
put message
Line 1,638: Line 2,291:
put characters 1 to -2 of message
put characters 1 to -2 of message
put the second to penultimate characters of message
put the second to penultimate characters of message
</syntaxhighlight>
</lang>
Output:
Output:
<lang sensetalk>
<syntaxhighlight lang="sensetalk">
☮Peace!
☮Peace!
Peace!
Peace!
☮Peace
☮Peace
Peace
Peace
</syntaxhighlight>
</lang>


=={{header|Sidef}}==
=={{header|Sidef}}==
Strip any characters:
Strip any characters:
<lang ruby>say "knight".substr(1); # strip first character
<syntaxhighlight lang="ruby">say "knight".substr(1); # strip first character
say "socks".substr(0, -1); # strip last character
say "socks".substr(0, -1); # strip last character
say "brooms".substr(1, -1); # strip both first and last characters
say "brooms".substr(1, -1); # strip both first and last characters
say "与今令".substr(1, -1); # => 今</lang>
say "与今令".substr(1, -1); # => 今</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,662: Line 2,315:


Strip graphemes:
Strip graphemes:
<lang ruby>var gstr = "J\x{332}o\x{332}s\x{332}e\x{301}\x{332}";
<syntaxhighlight lang="ruby">var gstr = "J\x{332}o\x{332}s\x{332}e\x{301}\x{332}";
say gstr-/^\X/; # strip first grapheme
say gstr-/^\X/; # strip first grapheme
say gstr-/\X\z/; # strip last grapheme
say gstr-/\X\z/; # strip last grapheme
say gstr.sub(/^\X/).sub(/\X\z/); # strip both first and last graphemes</lang>
say gstr.sub(/^\X/).sub(/\X\z/); # strip both first and last graphemes</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,676: Line 2,329:
{{works with|GNU Smalltalk}}
{{works with|GNU Smalltalk}}
These all use built-in collection methods that will work with any kind of ordered collection, not just Strings. There is no error checking. They will fail if the string is not at least two characters long.
These all use built-in collection methods that will work with any kind of ordered collection, not just Strings. There is no error checking. They will fail if the string is not at least two characters long.
<lang smalltalk>
<syntaxhighlight lang="smalltalk">
s := 'upraisers'.
s := 'upraisers'.
Transcript show: 'Top: ', s allButLast; nl.
Transcript show: 'Top: ', s allButLast; nl.
Transcript show: 'Tail: ', s allButFirst; nl.
Transcript show: 'Tail: ', s allButFirst; nl.
Transcript show: 'Without both: ', s allButFirst allButLast; nl.
Transcript show: 'Without both: ', s allButFirst allButLast; nl.
Transcript show: 'Without both using substring method: ', (s copyFrom: 2 to: s size - 1); nl.
Transcript show: 'Without both using substring method: ', (s copyFrom: 2 to: s size - 1); nl.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,691: Line 2,344:


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
<lang snobol4> "knight" len(1) rem . output ;* strip first character
<syntaxhighlight lang="snobol4"> "knight" len(1) rem . output ;* strip first character
"socks" rtab(1) . output ;* strip last character
"socks" rtab(1) . output ;* strip last character
"brooms" len(1) rtab(1) . output ;* strip both first and last characters</lang>
"brooms" len(1) rtab(1) . output ;* strip both first and last characters</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>- val str = "abcde";
<syntaxhighlight lang="sml">- val str = "abcde";
val str = "abcde" : string
val str = "abcde" : string
- String.substring(str, 1, String.size str - 1);
- String.substring(str, 1, String.size str - 1);
Line 1,703: Line 2,356:
val it = "abcd" : string
val it = "abcd" : string
- String.substring(str, 1, String.size str - 2);
- String.substring(str, 1, String.size str - 2);
val it = "bcd" : string</lang>
val it = "bcd" : string</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
Swift strings are native Unicode strings and do not index through the code points. Swift's <code>String.Index</code> refers to true Unicode characters (Unicode grapheme clusters). Swift standard library has generic functionality that not only works with strings, but also with any type that conforms to relevant protocols. The first method presented here uses generic functions from Swift standard library:
Swift strings are native Unicode strings and do not index through the code points. Swift's <code>String.Index</code> refers to true Unicode characters (Unicode grapheme clusters). Swift standard library has generic functionality that not only works with strings, but also with any type that conforms to relevant protocols. The first method presented here uses generic functions from Swift standard library:


<lang swift>let txt = "0123456789"
<syntaxhighlight lang="swift">let txt = "0123456789"
println(dropFirst(txt))
println(dropFirst(txt))
println(dropLast(txt))
println(dropLast(txt))
println(dropFirst(dropLast(txt)))</lang>
println(dropFirst(dropLast(txt)))</syntaxhighlight>
{{out}}
{{out}}
<pre>123456789
<pre>123456789
Line 1,717: Line 2,370:
12345678</pre>
12345678</pre>
The other method is slicing by range subscripting:
The other method is slicing by range subscripting:
<lang swift>let txt = "0123456789"
<syntaxhighlight lang="swift">let txt = "0123456789"
println(txt[txt.startIndex.successor() ..< txt.endIndex])
println(txt[txt.startIndex.successor() ..< txt.endIndex])
println(txt[txt.startIndex ..< txt.endIndex.predecessor()])
println(txt[txt.startIndex ..< txt.endIndex.predecessor()])
println(txt[txt.startIndex.successor() ..< txt.endIndex.predecessor()])</lang>
println(txt[txt.startIndex.successor() ..< txt.endIndex.predecessor()])</syntaxhighlight>
{{out}}
{{out}}
<pre>123456789
<pre>123456789
Line 1,726: Line 2,379:
12345678</pre>
12345678</pre>
Another way is mutating the string:
Another way is mutating the string:
<lang swift>var txt = "0123456789"
<syntaxhighlight lang="swift">var txt = "0123456789"
txt.removeAtIndex(txt.startIndex)
txt.removeAtIndex(txt.startIndex)
txt.removeAtIndex(txt.endIndex.predecessor())</lang>
txt.removeAtIndex(txt.endIndex.predecessor())</syntaxhighlight>
The above functions return what they remove.
The above functions return what they remove.
You can also extend String type and define BASIC-style functions:
You can also extend String type and define BASIC-style functions:
<lang swift>extension String {
<syntaxhighlight lang="swift">extension String {
/// Ensure positive indexes
/// Ensure positive indexes
Line 1,785: Line 2,438:
txt.right(1) // Right part without first character
txt.right(1) // Right part without first character
txt.left(-1) // Left part without last character
txt.left(-1) // Left part without last character
txt.mid(1,-1) // Middle part without first and last character</lang>
txt.mid(1,-1) // Middle part without first and last character</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>puts [string range "knight" 1 end]; # strip first character
<syntaxhighlight lang="tcl">puts [string range "knight" 1 end]; # strip first character
puts [string range "write" 0 end-1]; # strip last character
puts [string range "write" 0 end-1]; # strip last character
puts [string range "brooms" 1 end-1]; # strip both first and last characters</lang>
puts [string range "brooms" 1 end-1]; # strip both first and last characters</syntaxhighlight>


=={{header|TorqueScript}}==
=={{header|TorqueScript}}==
Line 1,813: Line 2,466:


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
str="upraisers"
str="upraisers"
Line 1,823: Line 2,476:
PRINT str2
PRINT str2
PRINT str3
PRINT str3
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,836: Line 2,489:
First ''or'' last character:
First ''or'' last character:


<lang bash>str='abcdefg'
<syntaxhighlight lang="bash">str='abcdefg'
echo "${str#?}" # Remove first char
echo "${str#?}" # Remove first char
echo "${str%?}" # Remove last char</lang>
echo "${str%?}" # Remove last char</syntaxhighlight>


First ''and'' last character:
First ''and'' last character:


: Only zsh supports nested string manipulation.
: Only zsh supports nested string manipulation.
: <lang bash>echo ${${str#?}%?} # Remove first & last chars</lang>
: <syntaxhighlight lang="bash">echo ${${str#?}%?} # Remove first & last chars</syntaxhighlight>
: bash and ksh, use substring expansion, from character index 1 for length of (string length) minus 2
: bash and ksh, use substring expansion, from character index 1 for length of (string length) minus 2
: <lang bash>echo "${s:1:${#s}-2}"</lang>
: <syntaxhighlight lang="bash">echo "${s:1:${#s}-2}"</syntaxhighlight>
: POSIX shells like dash, need a temp variable
: POSIX shells like dash, need a temp variable
: <lang bash>tmp=${s#?}; tmp=${tmp%?}; echo "$tmp"</lang>
: <syntaxhighlight lang="bash">tmp=${s#?}; tmp=${tmp%?}; echo "$tmp"</syntaxhighlight>


=={{header|Vala}}==
=={{header|Vala}}==
<lang vala>
<syntaxhighlight lang="vala">
// declare test string
// declare test string
string s = "Hello, world!";
string s = "Hello, world!";
Line 1,859: Line 2,512:
// remove first and last letters
// remove first and last letters
string s_first_last = s[1:s.length - 1];
string s_first_last = s[1:s.length - 1];
</syntaxhighlight>
</lang>


=={{header|VBScript}}==
=={{header|VBScript}}==
<lang VBScript>Function TopNTail(s,mode)
<syntaxhighlight lang="vbscript">Function TopNTail(s,mode)
Select Case mode
Select Case mode
Case "top"
Case "top"
TopNTail = Mid(s,2,Len(s)-1)
TopNTail = Mid(s,2,Len(s)-1)
Case "tail"
Case "tail"
TopNTail = Mid(s,1,Len(s)-1)
TopNTail = Mid(s,1,Len(s)-1)
Case "both"
Case "both"
TopNTail = Mid(s,2,Len(s)-2)
TopNTail = Mid(s,2,Len(s)-2)
End Select
End Select
End Function
End Function


WScript.Echo "Top: UPRAISERS = " & TopNTail("UPRAISERS","top")
WScript.Echo "Top: UPRAISERS = " & TopNTail("UPRAISERS","top")
WScript.Echo "Tail: UPRAISERS = " & TopNTail("UPRAISERS","tail")
WScript.Echo "Tail: UPRAISERS = " & TopNTail("UPRAISERS","tail")
WScript.Echo "Both: UPRAISERS = " & TopNTail("UPRAISERS","both")</lang>
WScript.Echo "Both: UPRAISERS = " & TopNTail("UPRAISERS","both")</syntaxhighlight>


{{out}}
{{out}}
Line 1,881: Line 2,534:
Tail: UPRAISERS = UPRAISER
Tail: UPRAISERS = UPRAISER
Both: UPRAISERS = PRAISER</pre>
Both: UPRAISERS = PRAISER</pre>

=={{header|Wren}}==
{{libheader|Wren-str}}
As Wren's string slicing and other built-in methods generally work at the byte level, we use the above module for this task which works at the code-point level.
<syntaxhighlight lang="wren">import "./str" for Str

var a = "Beyoncé"
var b = Str.delete(a, 0)
var len = a.codePoints.count
var c = Str.delete(a, len-1)
var d = Str.delete(c, 0)
for (e in [a, b, c, d]) System.print(e)</syntaxhighlight>

{{out}}
<pre>
Beyoncé
eyoncé
Beyonc
eyonc
</pre>


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\stdlib;
<syntaxhighlight lang="xpl0">include c:\cxpl\stdlib;
char S, P;
char S, P;
[S:= "Smiles";
[S:= "Smiles";
Line 1,894: Line 2,567:
Text(0, S+1); \first and last characters removed
Text(0, S+1); \first and last characters removed
CrLf(0);
CrLf(0);
]</lang>
]</syntaxhighlight>


Output:
Output:
Line 1,904: Line 2,577:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>"Smiles"[1,*] //-->miles
<syntaxhighlight lang="zkl">"Smiles"[1,*] //-->miles
"Smiles"[0,-1] //-->Smile
"Smiles"[0,-1] //-->Smile
"Smiles"[1,-1] //-->mile</lang>
"Smiles"[1,-1] //-->mile</syntaxhighlight>
[] format is [offset (zero based), length]. * means "to the end", a
[] format is [offset (zero based), length]. * means "to the end", a
negative number means from the end.
negative number means from the end.
Line 1,912: Line 2,585:
=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==


<lang zxbasic>10 PRINT FN f$("knight"): REM strip the first letter. You can also write PRINT "knight"(2 TO)
<syntaxhighlight lang="zxbasic">10 PRINT FN f$("knight"): REM strip the first letter. You can also write PRINT "knight"(2 TO)
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 1,919: Line 2,592:
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$)) </lang>
9020 DEF FN b$(a$)=FN l$(FN f$(a$)) </syntaxhighlight>


{{omit from|GUISS}}
{{omit from|GUISS}}

Revision as of 19:27, 27 February 2024

Task
Substring/Top and tail
You are encouraged to solve this task according to the task description, using any language you may know.

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


If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it.

The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.

Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.


Other tasks related to string operations:
Metrics
Counting
Remove/replace
Anagrams/Derangements/shuffling
Find/Search/Determine
Formatting
Song lyrics/poems/Mad Libs/phrases
Tokenize
Sequences



11l

Translation of: Python
print(‘knight’[1..])
print(‘socks’[0 .< (len)-1])
print(‘brooms’[1 .< (len)-1])
Output:
night
sock
room

360 Assembly

*        Substring/Top and tail    04/03/2017
SUBSTRTT CSECT
         USING  SUBSTRTT,R13       base register
         B      72(R15)            skip savearea
         DC     17F'0'             savearea
         STM    R14,R12,12(R13)    save previous context
         ST     R13,4(R15)         link backward
         ST     R15,8(R13)         link forward
         LR     R13,R15            set addressability
*
         XPRNT  S8,L'S8            print s8
         MVC    S7,S8+1            s7=substr(s8,2,7)
         XPRNT  S7,L'S7            print s7
         MVC    S7,S8              s7=substr(s8,1,7)
         XPRNT  S7,L'S7            print s7
         MVC    S6,S8+1            s6=substr(s8,2,6)
         XPRNT  S6,L'S6            print s6
*         
         L      R13,4(0,R13)       epilog
         LM     R14,R12,12(R13)    restore previous context
         XR     R15,R15            rc=0
         BR     R14                exit
S8       DC     CL8'12345678'
S7       DS     CL7
S6       DS     CL6
         YREGS
         END    SUBSTRTT
Output:
12345678
2345678
1234567
234567

ACL2

(defun str-rest (str)
   (coerce (rest (coerce str 'list)) 'string))

(defun rdc (xs)
   (if (endp (rest xs))
       nil
       (cons (first xs)
             (rdc (rest xs)))))

(defun str-rdc (str)
   (coerce (rdc (coerce str 'list)) 'string))

(str-rdc "string")
(str-rest "string")
(str-rest (str-rdc "string"))

Action!

PROC Main()
  CHAR ARRAY text="qwertyuiop"
  CHAR ARRAY res(20)
  BYTE n,m

  PrintF("Original string:%E  ""%S""%E%E",text)

  SCopyS(res,text,2,text(0))
  PrintF("String without the top:%E  ""%S""%E%E",res)

  SCopyS(res,text,1,text(0)-1)
  PrintF("String without the tail:%E  ""%S""%E%E",res)

  SCopyS(res,text,2,text(0)-1)
  PrintF("String without the top and the tail:%E  ""%S""%E%E",res)
RETURN
Output:

Screenshot from Atari 8-bit computer

Original string:
  "qwertyuiop"

String without the top:
  "wertyuiop"

String without the tail:
  "qwertyuio"

String without the top and the tail:
  "wertyuio"

Ada

with Ada.Text_IO;

procedure Remove_Characters is
   S: String := "upraisers";
   use Ada.Text_IO;
begin
   Put_Line("Full String:   """ & S & """");
   Put_Line("Without_First: """ & S(S'First+1 .. S'Last) & """");
   Put_Line("Without_Last:  """ & S(S'First   .. S'Last-1) & """");
   Put_Line("Without_Both:  """ & S(S'First+1 .. S'Last-1) & """");
end Remove_Characters;

Output:

Full String:   "upraisers"
Without_First: "praisers"
Without_Last:  "upraiser"
Without_Both:  "praiser"

With UTF8 support in Ada 2012 (Wide_Character of literals is automatic):

with Ada.Text_IO;
with Ada.Strings.UTF_Encoding.Wide_Strings;

procedure Remove_Characters
is
   use Ada.Text_IO;
   use Ada.Strings.UTF_Encoding;
   use Ada.Strings.UTF_Encoding.Wide_Strings;
   
   S : String := "upraisers";
   U : Wide_String := Decode (UTF_8_String'(S));
   
   function To_String (X : Wide_String)return String
   is
   begin
      return String (UTF_8_String'(Encode (X)));
   end To_String;
   
begin
   Put_Line
     (To_String
        ("Full String:   """ & U & """"));
   Put_Line
     (To_String
        ("Without_First: """ & U (U'First + 1 .. U'Last) & """"));
   Put_Line
     (To_String
        ("Without_Last:  """ & U (U'First   .. U'Last - 1) & """"));
   Put_Line
     (To_String
        ("Without_Both:  """ & U (U'First + 1 .. U'Last - 1) & """"));

end Remove_Characters;

Output:

Full String:   "upraisers"
Without_First: "praisers"
Without_Last:  "upraiser"
Without_Both:  "praiser"

Aime

o_text(delete("knights", 0));
o_newline();
o_text(delete("knights", -1));
o_newline();
o_text(delete(delete("knights", 0), -1));
o_newline();
Output:
nights
knight
night

ALGOL 68

Translation of: AWK
Works with: ALGOL 68 version Revision 1 - no extensions to language used.
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny.
#!/usr/local/bin/a68g --script #

STRING str="upraisers";
printf(($gl$,
  str,                      # remove no characters #
  str[LWB str+1:         ], # remove the first character #
  str[         :UPB str-1], # remove the last character #
  str[LWB str+1:UPB str-1], # remove both the first and last character #
  str[LWB str+2:         ], # remove the first 2 characters #
  str[         :UPB str-2], # remove the last 2 characters #
  str[LWB str+1:UPB str-2], # remove 1 before and 2 after #
  str[LWB str+2:UPB str-1], # remove 2 before and one after #
  str[LWB str+2:UPB str-2]  # remove both the first and last 2 characters #
))

Output:

upraisers
praisers
upraiser
praiser
raisers
upraise
praise
raiser
raise

Amazing Hopper

#include <hopper.h>
#proto showmessage(_X_)
main:
  s="message", t=s
  ++s, _show message(s)
  s=t
  --s, _show message(s)
  ++s, _show message(s)
{0}return

.locals
showmessage(_S_)
  {_S_,"\n"}print
back
Output:
essage
messag
essag

Apex

String strOrig = 'brooms';
String str1 = strOrig.substring(1, strOrig.length());
system.debug(str1);
String str2 = strOrig.substring(0, strOrig.length()-1);
system.debug(str2);
String str3 = strOrig.substring(1, strOrig.length()-1);
system.debug(str3);

// Regular Expressions approach
String strOrig = 'brooms';
String str1 = strOrig.replaceAll( '^.', '' );
system.debug(str1);
String str2 = strOrig.replaceAll( '.$', '' ) ;
system.debug(str2);
String str3 = strOrig.replaceAll( '^.|.$', '' );
system.debug(str3);
Output:
rooms

broom

room

AppleScript

set aString to "This is some text"

set stringLength to (count aString) -- The number of characters in the text.

-- AppleScript indices are 1-based. Ranges can be specified in several different ways.
if (stringLength > 1) then
    set substring1 to text 2 thru stringLength of aString
    -- set substring1 to text 2 thru -1 of aString
    -- set substring1 to text 2 thru end of aString
    -- set substring1 to text from character 2 to character stringLength of aString
    -- set substring1 to aString's text from 2 to -1
    -- Some combination of the above.
else
    set substring1 to ""
end if

if (stringLength > 1) then
    set substring2 to text 1 thru -2 of aString
else
    set substring2 to ""
end if

if (stringLength > 2) then
    set substring3 to text 2 thru -2 of aString
else
    set substring3 to ""
end if

return substring1 & linefeed & substring2 & linefeed & substring3
Output:
"his is some text
This is some tex
his is some tex"

Arturo

knight: "knight"
socks: "socks"
brooms: "brooms"

print drop knight.                      ; strip first character
print slice knight 1 (size knight)-1    ; alternate way to strip first character

print chop socks                        ; strip last character
print take socks (size socks)-1         ; alternate way to strip last character
print slice socks 0 (size socks)-2      ; yet another way to strip last character

print chop drop brooms                  ; strip both first and last characters
print slice brooms 1 (size brooms)-2    ; alternate way to strip both first and last characters
Output:
night
night
sock
sock
sock
room
room

AutoHotkey

myString := "knights"
MsgBox % SubStr(MyString, 2)
MsgBox % SubStr(MyString, 1, StrLen(MyString)-1)
MsgBox % SubStr(MyString, 2, StrLen(MyString)-2)

AWK

BEGIN {
  mystring="knights"
  print substr(mystring,2)                       # remove the first letter
  print substr(mystring,1,length(mystring)-1)    # remove the last character
  print substr(mystring,2,length(mystring)-2)    # remove both the first and last character
}

BASIC

10 PRINT FN F$("KNIGHTS"): 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 END
 
9000 DEF FN F$(A$)=RIGHT$(A$,LEN(A$)-1)
9010 DEF FN L$(A$)=LEFT$(A$,LEN(A$)-1)
9020 DEF FN B$(A$)=FN L$(FN F$(A$))

Applesoft BASIC

10 s$ = "Rosetta Code"
20 PRINT s$
30 PRINT MID$(s$,2)           
40 PRINT LEFT$(s$,LEN(s$)-1)  
50 PRINT MID$(s$,2,LEN(s$)-2)

Chipmunk Basic

Works with: Chipmunk Basic version 3.6.4
10 s$ = "Rosetta Code"
20 print s$
30 print mid$(s$,2)'strip first
40 print left$(s$,len(s$)-1)'strip last
50 print mid$(s$,2,len(s$)-2)'strip first and last

MSX Basic

Works with: GW-BASIC
10 S$ = "Rosetta Code"
20 PRINT S$
30 PRINT MID$(S$, 2)              'strip first
40 PRINT LEFT$(S$, LEN(S$) - 1)   'strip last
50 PRINT MID$(S$, 2, LEN(S$) - 2) 'strip first and last

QBasic

Works with: QBasic version 1.1
Works with: QuickBasic version 4.5
s$ = "Rosetta Code"

PRINT s$
PRINT MID$(s$, 2)               'strip first
PRINT LEFT$(s$, LEN(s$) - 1)    'strip last
PRINT MID$(s$, 2, LEN(s$) - 2)  'strip first and last

BASIC256

s$ = "Rosetta Code"

print s$
PRINT MID$(s$, 2)               'strip first
PRINT LEFT$(s$, LEN(s$) - 1)    'strip last
PRINT MID$(s$, 2, LEN(s$) - 2)  'strip first and last

True BASIC

LET s$ = "Rosetta Code"
PRINT s$
PRINT (s$)[2:maxnum]              !strip first
PRINT (s$)[1:len(s$)-1]           !strip last
PRINT (s$)[2:2+len(s$)-2-1]       !strip first and last
END

XBasic

Works with: Windows XBasic
PROGRAM	"Substring"
VERSION	"0.0000"

DECLARE FUNCTION  Entry ()

FUNCTION  Entry ()
s$ = "Rosetta Code"

PRINT s$
PRINT MID$(s$, 2)               'strip first
PRINT LEFT$(s$, LEN(s$) - 1)    'strip last
PRINT MID$(s$, 2, LEN(s$) - 2)  'strip first and last

END FUNCTION
END PROGRAM

Yabasic

s$ = "Rosetta Code"

print s$
PRINT MID$(s$, 2)               'strip first
PRINT LEFT$(s$, LEN(s$) - 1)    'strip last
PRINT MID$(s$, 2, LEN(s$) - 2)  'strip first and last

IS-BASIC

100 LET S$="Knights"
110 PRINT S$(2:)
120 PRINT S$(:LEN(S$)-1)
130 PRINT S$(2:LEN(S$)-1)

Sinclair ZX81 BASIC

Note that strings are indexed from 1.

10 REM STRING SLICING EXAMPLE
20 LET S$="KNIGHTS"
30 REM WITH FIRST CHARACTER REMOVED:
40 PRINT S$(2 TO )
50 REM WITH LAST CHARACTER REMOVED:
60 PRINT S$( TO LEN S$-1)
70 REM WITH BOTH REMOVED:
80 PRINT S$(2 TO LEN S$-1)
Output:
NIGHTS
KNIGHT
NIGHT

Microsoft Small Basic

When I tried using Unicode characters, it printed question marks, though ASCII works fine.

string = "Small Basic"
TextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) 'Without the first character
TextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) 'Without the last character
TextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2)) 'Without the first and last characters
Output:
mall Basic
Small Basi
mall Basi

BQN

Drop() is the main function used here.

  str  "substring"
"substring"
  1str
"ubstring"
  ¯1str
"substrin"
  1¯1str
"ubstrin"

BBC BASIC

      s$ = "Rosetta Code"
      PRINT MID$(s$, 2)
      PRINT LEFT$(s$)
      PRINT LEFT$(MID$(s$, 2))

Bracmat

Bracmat uses UTF-8 internally. The function utf fails if its argument isn't a valid UTF-8 multibyte string, but in two slightly different ways: an indefinite and a definite way. If the argument does not have the required number of bytes but otherwise seems to be ok, Bracmat's backtacking mechanism lenghtens the argument and then calls utf again. This is repeated until utf either succeeds or definitely fails. The code is far from efficient.

(substringUTF-8=
  @( Δημοτική
   : (%?a&utf$!a) ?"String with first character removed"
   )
& @( Δημοτική
   : ?"String with last character removed" (?z&utf$!z)
   )
& @( Δημοτική
   :   (%?a&utf$!a)
       ?"String with both the first and last characters removed"
       (?z&utf$!z)
   )
&   out
  $ ("String with first character removed:" !"String with first character removed")
&   out
  $ ("String with last character removed:" !"String with last character removed")
&   out
  $ ( "String with both the first and last characters removed:"
      !"String with both the first and last characters removed"
    ));
!substringUTF-8
String with first character removed: ημοτική
String with last character removed: Δημοτικ
String with both the first and last characters removed: ημοτικ

If the string is known to consist of 8-byte characters, we can use a simpler method. Essential are the % and @ prefixes. The % prefix matches 1 or more elements (bytes, in the case of string pattern matching), while @ matches 0 or 1 elements. In combination these prefixes match 1 and only 1 byte.

(substring-8-bit=
  @("8-bit string":%@ ?"String with first character removed")
& @("8-bit string":?"String with last character removed" @)
& @( "8-bit string"
   : %@ ?"String with both the first and last characters removed" @
   )
&   out
  $ ("String with first character removed:" !"String with first character removed")
&   out
  $ ("String with last character removed:" !"String with last character removed")
&   out
  $ ( "String with both the first and last characters removed:"
      !"String with both the first and last characters removed"
    ));
!substring-8-bit
String with first character removed: -bit string
String with last character removed: 8-bit strin
String with both the first and last characters removed: -bit strin

Burlesque

blsq ) "RosettaCode"[-
"osettaCode"
blsq ) "RosettaCode"-]
'R
blsq ) "RosettaCode"~]
"RosettaCod"
blsq ) "RosettaCode"[~
'e
blsq ) "RosettaCode"~-
"osettaCod"

C

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int main( int argc, char ** argv ){
  const char * str_a = "knight";
  const char * str_b = "socks";
  const char * str_c = "brooms";

  char * new_a = malloc( strlen( str_a ) - 1 );
  char * new_b = malloc( strlen( str_b ) - 1 );
  char * new_c = malloc( strlen( str_c ) - 2 );

  strcpy( new_a, str_a + 1 );
  strncpy( new_b, str_b, strlen( str_b ) - 1 );
  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );

  printf( "%s\n%s\n%s\n", new_a, new_b, new_c );

  free( new_a );
  free( new_b );
  free( new_c );

  return 0;
}

Result:

night
sock
room

ANSI C provides little functionality for text manipulation outside of string.h. While a number of libraries for this purpose have been written, this example uses only ANSI C.

C#

using System;

class Program
{
    static void Main(string[] args)
    {
        string testString = "test";
        Console.WriteLine(testString.Substring(1));
        Console.WriteLine(testString.Substring(0, testString.Length - 1));
        Console.WriteLine(testString.Substring(1, testString.Length - 2));
    }
}

Result:

est
tes
es

C++

#include <string>
#include <iostream>

int main( ) {
   std::string word( "Premier League" ) ;
   std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ;
   std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ;
   std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ;
   return 0 ;
}

Output:

Without first letter: remier League !
Without last letter: Premier Leagu !
Without first and last letter: remier Leagu !

Clojure

; using substring:
user=> (subs "knight" 1)
"night"
user=> (subs "socks" 0 4)
"sock"
user=> (.substring "brooms" 1 5)
"room"

; using rest and drop-last:
user=> (apply str (rest "knight"))
"night"
user=> (apply str (drop-last "socks"))
"sock"
user=> (apply str (rest (drop-last "brooms")))
"room"

COBOL

       identification division.
       program-id. toptail.

       data division.
       working-storage section.
       01 data-field.
          05 value "[this is a test]".

       procedure division.
       sample-main.
       display data-field
      *> Using reference modification, which is (start-position:length)
       display data-field(2:)
       display data-field(1:length of data-field - 1)
       display data-field(2:length of data-field - 2)
       goback.
       end program toptail.
Output:
prompt$ cobc -xj toptail.cob
[this is a test]
this is a test]
[this is a test
this is a test

Common Lisp

subseq will signal an error if you provide invalid start or end values.

> (defvar *str* "∀Ꮺ✤Л◒")
*STR*
> (subseq *str* 1) ; remove first character
"Ꮺ✤Л◒"
> (subseq *str* 0 (1- (length *str*))) ; remove last character
"∀Ꮺ✤Л"
> (subseq *str* 1 (1- (length *str*))) ; remove first and last character
"Ꮺ✤Л"

D

Version for ASCII strings or Unicode dstrings:

import std.stdio;

void main() {
    // strip first character
    writeln("knight"[1 .. $]);

    // strip last character
    writeln("socks"[0 .. $ - 1]);

    // strip both first and last characters
    writeln("brooms"[1 .. $ - 1]);
}
Output:
night
sock
room

Dart

void main() {
  String word = "Premier League";
  print("Without first letter: ${word.substring(1)} !");
  print("Without last letter: ${word.substring(0, word.length - 1)} !");
  print("Without first and last letter: ${word.substring(1, word.length - 1)} !");
}
Output:
Same as C++ entry.

Delphi

program TopAndTail;

{$APPTYPE CONSOLE}

const
  TEST_STRING = '1234567890';
begin
  Writeln(TEST_STRING);                                    // full string
  Writeln(Copy(TEST_STRING, 2, Length(TEST_STRING)));      // first character removed
  Writeln(Copy(TEST_STRING, 1, Length(TEST_STRING) - 1));  // last character removed
  Writeln(Copy(TEST_STRING, 2, Length(TEST_STRING) - 2));  // first and last characters removed

  Readln;
end.

EasyLang

s$ = "Easylang"
print substr s$ 1 (len s$ - 1)
print substr s$ 2 (len s$ - 1)
print substr s$ 2 (len s$ - 2)
Output:
Easylan
asylang
asylan

Eero

#import <Foundation/Foundation.h>

int main()
  autoreleasepool

    s := 'knight'
    Log( '%@', s[1 .. s.length-1] )  // strip first character

    s = 'socks'
    Log( '%@', s[0 .. s.length-2] )  // strip last character
   
    s = 'brooms'   
    Log( '%@', s[1 .. s.length-2] )  // strip both first and last characters

    s = 'Δημοτική'   
    Log( '%@', s[1 .. s.length-2] )  // strip both first and last characters

  return 0

Output:

2013-09-04 17:08:09.453 a.out[2257:507] night
2013-09-04 17:08:09.454 a.out[2257:507] sock
2013-09-04 17:08:09.454 a.out[2257:507] room
2013-09-04 17:08:09.455 a.out[2257:507] ημοτικ

Elena

ELENA 4.x :

import extensions;
 
public program()
{
    var testString := "test";
 
    console.printLine(testString.Substring(1));
    console.printLine(testString.Substring(0, testString.Length - 1));
    console.printLine(testString.Substring(1, testString.Length - 2))
}
Output:
est
tes
es

Elixir

iex(1)> str = "abcdefg"
"abcdefg"
iex(2)> String.slice(str, 1..-1)
"bcdefg"
iex(3)> String.slice(str, 0..-2)
"abcdef"
iex(4)> String.slice(str, 1..-2)
"bcdef"

Emacs Lisp

(let ((string "top and tail"))
  (substring string 1) ;=> "op and tail"
  (substring string 0 (1- (length string))) ;=> "top and tai"
  (substring string 1 (1- (length string)))) ;=> "op and tai"

Erlang

1> Str = "Hello".
"Hello"
2> string:sub_string(Str, 2).                   % To strip the string from the right by 1
"ello"
3> string:sub_string(Str, 1, length(Str)-1).    % To strip the string from the left by 1
"Hell"
4> string:sub_string(Str, 2, length(Str)-1).    % To strip the string from both sides by 1
"ell"

Euphoria

function strip_first(sequence s)
    return s[2..$]
end function

function strip_last(sequence s)
    return s[1..$-1]
end function

function strip_both(sequence s)
    return s[2..$-1]
end function

puts(1, strip_first("knight"))  -- strip first character
puts(1, strip_last("write"))    -- strip last character
puts(1, strip_both("brooms"))   -- strip both first and last characters

F#

[<EntryPoint>]
let main args =
    let s = "一二三四五六七八九十"
    printfn "%A" (s.Substring(1))
    printfn "%A" (s.Substring(0, s.Length - 1))
    printfn "%A" (s.Substring(1, s.Length - 2))
    0

Output

"二三四五六七八九十"
"一二三四五六七八九"
"二三四五六七八九"

Factor

USING: io kernel sequences ;
"Rosetta code" [ rest ] [ but-last ] [ rest but-last ] tri
[ print ] tri@
Output:
osetta code
Rosetta cod
osetta cod

Forth

In Forth, strings typically take up two cells on the stack, diagrammed ( c-addr u ), with C-ADDR the address of the string and U its length. Dropping leading and trailing characters then involves simple mathematical operations on the address or length, without mutating or copying the string.

: hello ( -- c-addr u )
  s" Hello" ;  

hello 1 /string type     \ => ello

hello 1- type            \ => hell

hello 1 /string 1- type  \ => ell

This works for ASCII, and a slight variation (2 instead of 1 per character) will suffice for BIG5, GB2312, and like, but Unicode-general code can use +X/STRING and X\STRING- from Forth-200x's XCHAR wordset.

Fortran

program substring

  character(len=5) :: string
  string = "Hello"
  
  write (*,*) string
  write (*,*) string(2:)
  write (*,*) string( :len(string)-1)
  write (*,*) string(2:len(string)-1)

end program substring

FreeBASIC

' FB 1.05.0 Win64

Dim s As String  = "panda"
Dim s1 As String = Mid(s, 2)
Dim s2 As String = Left(s, Len(s) - 1)
Dim s3 As String = Mid(s, 2, Len(s) - 2)
Print s
Print s1
Print s2
Print s3
Sleep
Output:
panda
anda
pand
and


FutureBasic

void local fn DoIt
  CFStringRef s = @"knights"
  print s
  CFStringRef s1 = mid(s, 1, len(s) - 1)
  print s1
  CFStringRef s2 = left(s,   len(s) - 1)
  print s2
  CFStringRef s3 = mid(s, 1, len(s) - 2)
  print s3
end fn

fn DoIt

HandleEvents
Output:
knights
nighs
knight
night


Go

Go strings are byte arrays that can hold whatever you want them to hold. Common contents are ASCII and UTF-8. You use different techniques depending on how you are interpreting the string. The utf8 package functions shown here allows efficient extraction of first and last runes without decoding the entire string.

package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    // ASCII contents:  Interpreting "characters" as bytes.
    s := "ASCII"
    fmt.Println("String:                ", s)
    fmt.Println("First byte removed:    ", s[1:])
    fmt.Println("Last byte removed:     ", s[:len(s)-1])
    fmt.Println("First and last removed:", s[1:len(s)-1])
    // UTF-8 contents:  "Characters" as runes (unicode code points)
    u := "Δημοτική"
    fmt.Println("String:                ", u)
    _, sizeFirst := utf8.DecodeRuneInString(u)
    fmt.Println("First rune removed:    ", u[sizeFirst:])
    _, sizeLast := utf8.DecodeLastRuneInString(u)
    fmt.Println("Last rune removed:     ", u[:len(u)-sizeLast])
    fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast])
}

Output:

String:                 ASCII
First byte removed:     SCII
Last byte removed:      ASCI
First and last removed: SCI
String:                 Δημοτική
First rune removed:     ημοτική
Last rune removed:      Δημοτικ
First and last removed: ημοτικ

Golfscript

When I tried using Unicode characters, the interpreter generated a mess, though ASCII works fine.

"Golfscript"(;n
"Golfscript");n
"Golfscript"(;);
Output:
olfscript
Golfscrip
olfscrip

Groovy

Solution:

def top  = { it.size() > 1 ? it[0..-2] : '' }
def tail = { it.size() > 1 ? it[1..-1] : '' }

Test:

def testVal = 'upraisers'
println """
original: ${testVal}
top:      ${top(testVal)}
tail:     ${tail(testVal)}
top&tail: ${tail(top(testVal))}
"""

Output:

original: upraisers
top:      upraiser
tail:     praisers
top&tail: praiser

GW-BASIC

10 A$="knight":B$="socks":C$="brooms"
20 PRINT MID$(A$,2)
30 PRINT LEFT$(B$,LEN(B$)-1)
40 PRINT MID$(C$,2,LEN(C$)-2)

Haskell

-- We define the functions to return an empty string if the argument is too
-- short for the particular operation.

remFirst, remLast, remBoth :: String -> String

remFirst "" = ""
remFirst cs = tail cs

remLast "" = ""
remLast cs = init cs

remBoth (c:cs) = remLast cs
remBoth  _     = ""

main :: IO ()
main = do
  let s = "Some string."  
  mapM_ (\f -> putStrLn . f $ s) [remFirst, remLast, remBoth]

Alternative solution with builtin functions:

word = "knights"

main = do
    -- You can drop the first item
    -- using `tail`
    putStrLn (tail word)

    -- The `init` function will drop
    -- the last item
    putStrLn (init word)

    -- We can combine these two to drop
    -- the last and the first characters
    putStrLn (middle word)

-- You can combine functions using `.`,
-- which is pronounced "compose" or "of"
middle = init . tail

In short:

main :: IO ()
main = mapM_ print $ [tail, init, init . tail] <*> ["knights"]
Output:
"nights"
"knight"
"night"

Icon and Unicon

The task is accomplished by sub-stringing.

procedure main()
write(s := "knight"," --> ", s[2:0])  # drop 1st char
write(s := "sock"," --> ", s[1:-1])   # drop last
write(s := "brooms"," --> ", s[2:-1]) # drop both
end

It could also be accomplished (less clearly) by assigning into the string as below. Very awkward for both front and back.

write(s := "knight"," --> ", s[1] := "", s)  # drop 1st char

J

The monadic primitives }. (Behead) and }: (Curtail) are useful for this task.

Example use:

   }. 'knight'      NB. drop first item
night
   }: 'socks'       NB. drop last item
sock
   }: }. 'brooms'   NB. drop first and last items
room

Java

I solve this problem two ways. First I use substring which is relatively fast for small strings, since it simply grabs the characters within a set of given bounds. The second uses regular expressions, which have a higher overhead for such short strings, but work correctly with all Unicode code points, not just those in the Basic Multilingual Plane.

public class RM_chars {
  public static void main( String[] args ){
    System.out.println( "knight".substring( 1 ) );
    System.out.println( "socks".substring( 0, 4 ) );
    System.out.println( "brooms".substring( 1, 5 ) );
      // first, do this by selecting a specific substring
      // to exclude the first and last characters
    
    System.out.println( "knight".replaceAll( "^.", "" ) );
    System.out.println( "socks".replaceAll( ".$", "" ) );
    System.out.println( "brooms".replaceAll( "^.|.$", "" ) );
      // then do this using a regular expressions
  }
}

Results:

night
sock
room
night
sock
room

Nearly all current solutions for this task fail to work correctly: the task says "The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16." The code below works correctly with all Unicode characters, without using regular expressions as the above program does.

public class SubstringTopAndTail {
  public static void main( String[] args ){
    var s = "\uD83D\uDC0Eabc\uD83D\uDC0E";  // Horse emoji, a, b, c, horse emoji: "🐎abc🐎"

    var sizeOfFirstChar = Character.isSurrogate(s.charAt(0)) ? 2 : 1;
    var sizeOfLastChar = Character.isSurrogate(s.charAt(s.length() - 1)) ? 2 : 1;

    var removeFirst = s.substring(sizeOfFirstChar);
    var removeLast = s.substring(0, s.length() - sizeOfLastChar);
    var removeBoth = s.substring(sizeOfFirstChar, s.length() - sizeOfLastChar);

    System.out.println(removeFirst);
    System.out.println(removeLast);
    System.out.println(removeBoth);
  }
}

Results:

abc🐎
🐎abc
abc

JavaScript

alert("knight".slice(1));       // strip first character
alert("socks".slice(0, -1));    // strip last character
alert("brooms".slice(1, -1));   // strip both first and last characters

Joy

DEFINE
  dropfirst == 1 drop;
  droplast == dup size pred take.

"abcd" dropfirst.
"abcd" droplast.
"abcd" dropfirst droplast.

If a string is known to be non-empty, the rest operator could be used instead of dropfirst.

Output:
"bcd"
"abc"
"bc"

jq

jq uses 0-based indexing, so [1:] yields all but the first character, it being understood that data strings in jq are JSON strings. [0:-1], which can be abbreviated to [:-1], yields all but the last character, and so on. Here are some examples:

"一二三四五六七八九十"[1:]' => "二三四五六七八九十"

"一二三四五六七八九十"[:-1]' => "一二三四五六七八九"

"一二三四五六七八九十"[1:-1]' => "二三四五六七八九"

"a"[1:-1] # => ""

Recent versions of jq also have regular expression support, with named captures. This leads to many other possibilities, e.g.

"abc" | capture( ".(?<monkey>.*)." ).monkey => "b"

Julia

julia> "My String"[2:end] # without first character
"y String"

julia> "My String"[1:end-1] # without last character
"My Strin"

julia> "My String"[2:end-1] # without first and last characters
"y Strin"

K

K provides the system function _di to delete an element at a specified index. The following code is implemented using this feature.

    s: "1234567890"
"1234567890"
    s _di 0 /Delete 1st character
"234567890"
    s _di -1+#s /Delete last character
"123456789"
    (s _di -1+#s) _di 0 /String with both 1st and last character removed
"23456789"

Another way to implement without using the above system function:

    s: "1234567890"
"1234567890"
    1 _ s  /Delete 1st character
"234567890"
    -1 _ s /Delete last character
"123456789"
    1 - -1 _ s /Delete 1st and last character
"23456789"

Kotlin

// version 1.0.6
fun main(args: Array<String>) {
    val s = "Rosetta"
    println(s.drop(1))
    println(s.dropLast(1))
    println(s.drop(1).dropLast(1))
}
Output:
osetta
Rosett
osett

Lambdatalk

{def R rosetta}                               -> rosetta

{W.rest {R}}                                  ->  osetta
{W.reverse {W.rest {W.reverse {R}}}}          -> rosett
{W.rest {W.reverse {W.rest {W.reverse {R}}}}} ->  osett

or 

{W.slice 1 {W.length {R}} {R}}                ->  osetta
{W.slice 0 {- {W.length {R}} 1} {R}}          -> rosett
{W.slice 1 {- {W.length {R}} 1} {R}}          ->  osett

{def J ストリング}                              -> ストリング

{W.rest {J}}                                  ->   トリング
{W.reverse {W.rest {W.reverse {J}}}}          -> ストリン
{W.rest {W.reverse {W.rest {W.reverse {J}}}}} ->   トリン

Lasso

local(str = 'The quick grey rhino jumped over the lazy green fox.')

// String with first character removed
string_remove(#str,-startposition=1,-endposition=1)

// String with last character removed
string_remove(#str,-startposition=#str->size,-endposition=#str->size)

// String with both the first and last characters removed
string_remove(string_remove(#str,-startposition=#str->size,-endposition=#str->size),-startposition=1,-endposition=1)
Output:
he quick grey rhino jumped over the lazy green fox.
The quick grey rhino jumped over the lazy green fox
he quick grey rhino jumped over the lazy green fox
local(mystring = 'ÅÜÄÖカ')

#mystring -> remove(1,1)
#mystring
'<br />'
#mystring -> remove(#mystring -> size,1)
#mystring
'<br />'
#mystring -> remove(1,1)& -> remove(#mystring -> size,1)
#mystring

-> ÜÄÖカ

ÜÄÖ

Ä ==Lasso==

local(str = 'The quick grey rhino jumped over the lazy green fox.')

// String with first character removed
string_remove(#str,-startposition=1,-endposition=1)
// > he quick grey rhino jumped over the lazy green fox.

// String with last character removed
string_remove(#str,-startposition=#str->size,-endposition=#str->size)
// > The quick grey rhino jumped over the lazy green fox

// String with both the first and last characters removed
string_remove(string_remove(#str,-startposition=#str->size,-endposition=#str->size),-startposition=1,-endposition=1)
// > he quick grey rhino jumped over the lazy green fox

Liberty BASIC

string$ = "Rosetta Code"
Print Mid$(string$, 2)
Print Left$(string$, (Len(string$) - 1))
Print Mid$(string$, 2, (Len(string$) - 2))

LiveCode

put "pple" into x
answer char 2 to len(x) of x // pple
answer char 1 to -2 of x  // ppl
answer char 2 to -2 of x // ppl

Locomotive Basic

10 a$="knight":b$="socks":c$="brooms"
20 PRINT MID$(a$,2)
30 PRINT LEFT$(b$,LEN(b$)-1)
40 PRINT MID$(c$,2,LEN(c$)-2)

make "s "|My string|
print butfirst :s
print butlast :s
print butfirst butlast :s

Logtalk

Using atoms for representing strings:

:- object(top_and_tail).

    :- public(test/1).
    test(String) :-
        sub_atom(String, 1, _, 0, MinusTop),
        write('String with first character cut: '), write(MinusTop), nl,
        sub_atom(String, 0, _, 1, MinusTail),
        write('String with last character cut: '), write(MinusTail), nl,
        sub_atom(String, 1, _, 1, MinusTopAndTail),
        write('String with first and last characters cut: '), write(MinusTopAndTail), nl.

:- end_object.

Sample output:

| ?- top_and_tail::test('Rosetta').
String with first character cut: osetta
String with last character cut: Rosett
String with first and last characters cut: osett
yes

Lua

print (string.sub("knights",2))    -- remove the first character
print (string.sub("knights",1,-2))    -- remove the last character
print (string.sub("knights",2,-2))    -- remove the first and last characters

Maple

There are several ways to do this. The first is, I think, the simplest.

> s := "some string":
> s[2..-1];
                              "ome string"

> s[1..-2];
                              "some strin"

> s[2..-2];
                              "ome strin"

The same functionality exists in the form of a procedure:

> substring( s, 2 .. -1 );
                              "ome string"

> substring( s, 1 .. -2 );
                              "some strin"

> substring( s, 2 .. -2 );
                              "ome strin"

Furthermore, there is a slightly different version in the "StringTools" package:

> use StringTools in
>     SubString( s, 2 .. -1 );
>     SubString( s, 1 .. -1 );
>     SubString( s, 2 .. -2 ) 
> end use;
                              "ome string"

                             "some string"

                              "ome strin"

(The difference between "substring" and "StringTools:-SubString" lies in how each treats a name as input; the former returns a name, while the latter returns a string.)

Mathematica/Wolfram Language

StringDrop["input string",1]
StringDrop["input string",-1]
StringTake["input string",{2,-2}]

MATLAB / Octave

The following case will not handle UTF-8. However, Matlab supports conversion of utf-8 to utf-16 using native2unicode().

 
    % String with first character removed
    str(2:end)
    % String with last character removed
    str(1:end-1)
    % String with both the first and last characters removed 
    str(2:end-1)

MiniScript

test = "This thing"
print test[1:]
print test[:-1]
print test[1:-1]
Output:
his thing
This thin
his thin

MIPS Assembly

Thanks to Chibialiens for the header/footer, font, and print routines.

.include "\SrcAll\Header.asm"
.include "\SrcAll\BasicMacros.asm"
.include "\SrcALL\AdvancedMacros.asm"
.include "\SrcALL\MemoryMap.asm"

; .definelabel UserRam,0xA0010000		(this is defined in the header)

CursorX equ 0x100 ;offset from label UserRam
CursorY equ 0x101 ;offset from label UserRam

main:
	jal Cls
	nop
	
	la a0,MyString
	la a1,UserRam+0x1000
	push a0
	push a1
		jal strcpy
		addiu a0,1		;branch delay slot - increment base address prior to branching
	pop a0				;deliberately pop in the "wrong order"
	pop a1				;because printString uses $a0
	
	jal PrintString
	nop
	jal NewLine
	nop
	
	
	
	la a0,MyString
	la a1,UserRam+0x1000
	
	push a0
	push a1
		jal strcpy
		nop				;branch delay slot
		;after a strcpy, a0/a1 both point to the null terminator
		subiu a1,1
		move t0,zero
		sb t0,(a1)
		.ifdef buildPSX
			nop		;load delay slot
		.endif
	pop a0
	pop a1
	
	jal PrintString
	nop
	jal NewLine
	nop
	
	la a0,MyString
	la a1,UserRam+0x1000
	
	push a0
	push a1
		jal strcpy
		addiu a0,1	;branch delay slot
		;after a strcpy, a0/a1 both point to the null terminator
		subiu a1,1
		move t0,zero
		sb t0,(a1)
		.ifdef buildPSX
			nop		;load delay slot
		.endif
	pop a0
	pop a1
	
	jal PrintString
	nop
	jal NewLine
	nop
	
	
halt:
	nop
	j halt
	nop
	
	
MyString:
	.ascii "Hello World"
	.byte 0
	.align 4
	
MyFont:

.ifdef buildn64				
	.incbin "\ResN64\ChibiAkumas.fnt"
.endif
.ifdef buildPSX				
	.incbin "\ResPSX\ChibiAkumas.fnt"
.endif

.include "\SrcALL\graphics.asm"
.include "\SrcAll\monitor.asm"
.include "\SrcALL\Multiplatform_Math_Integer.asm"
.include "\SrcALL\BasicFunctions_v2.asm"
.include "\SrcN64\Footer.asm"
Output:
ello World
Hello Worl
ello Worl

Screenshot of PlayStation 1 Emulator

Neko

Neko strings are mutable, fixed length buffers. The $ssize builtin uses the allocated size, not any internal sentinel terminator byte. With literals, the allocated size is the size of the data between quotes, i.e. no NUL byte appended.

$ssub sub-string takes string, position (zero-relative), length arguments.

/**
 Subtring/Top-Tail in Neko
*/

var data = "[this is a test]"
var len = $ssize(data)

$print(data, "\n")
$print($ssub(data, 1, len - 1), "\n")
$print($ssub(data, 0, len - 1), "\n")
$print($ssub(data, 1, len - 2), "\n")
Output:
prompt$ nekoc toptail.neko
prompt$ neko toptail.n
[this is a test]
this is a test]
[this is a test
this is a test

Nemerle

using System;
using System.Console;

module RemoveChars
{
    Main() : void
    {
        def str = "*A string*";
        def end = str.Remove(str.Length - 1);  // from pos to end
        def beg = str.Remove(0, 1);            // start pos, # of chars to remove
        def both = str.Trim(array['*']);       // with Trim() you need to know what char's you're removing
        
        WriteLine($"$str -> $beg -> $end -> $both");
    }
}

NetRexx

/**********************************************************************
* 02.08.2013 Walter Pachl  translated from REXX
**********************************************************************/
z = 'abcdefghijk'
l=z.length()
say '                  the original string =' z
If l>=1 Then Do
  Say 'string first        character removed =' z.substr(2)
  say 'string         last character removed =' z.left(l-1)
  End
If l>=2 Then
  Say 'string first & last character removed =' z.substr(2,l-2)

NewLISP

(let (str "rosetta")
  ;; strip first char
  (println (1 str))
  ;; strip last char
  (println (0 -1 str))
  ;; strip both first and last characters
  (println (1 -1 str)))

Nim

import unicode

let s = "Hänsel  ««: 10,00€"
echo "Original: ", s
echo "With first character removed: ", s.runeSubStr(1)
echo "With last character removed: ", s.runeSubStr(0, s.runeLen - 1)
echo "With first and last characters removed: ", s.runeSubStr(1, s.runeLen - 2)
# Using the runes type and slices
let r = s.toRunes
echo "With first and last characters removed (other way): ", r[1 .. ^2]
Output:
Original: Hänsel  ««: 10,00€
With first character removed: änsel  ««: 10,00€
With last character removed: Hänsel  ««: 10,00
With first and last characters removed: änsel  ««: 10,00
With first and last characters removed (other way): änsel  ««: 10,00

Objeck

bundle Default {
   class TopTail {
      function : Main(args : System.String[]) ~ Nil {
         string := "test";
         string->SubString(1, string->Size() - 1)->PrintLine();
         string->SubString(string->Size() - 1)->PrintLine();
         string->SubString(1, string->Size() - 2)->PrintLine();
      }
   }
}

OCaml

let strip_first_char str =
  if str = "" then "" else
  String.sub str 1 ((String.length str) - 1)

let strip_last_char str =
  if str = "" then "" else
  String.sub str 0 ((String.length str) - 1)

let strip_both_chars str =
  match String.length str with
  | 0 | 1 | 2 -> ""
  | len -> String.sub str 1 (len - 2)

let () =
  print_endline (strip_first_char "knight");
  print_endline (strip_last_char "socks");
  print_endline (strip_both_chars "brooms");
;;

Oforth

: topAndTail(s)
    s right(s size 1-) println
    s left(s size 1-) println
    s extract(2, s size 1- ) println ;
Output:
topAndTail("MyString")
yString
MyStrin
yStrin

PARI/GP

df(s)=concat(vecextract(Vec(s),1<<#s-2));
dl(s)=concat(vecextract(Vec(s),1<<(#s-1)-1));
db(s)=concat(vecextract(Vec(s),1<<(#s-1)-2));

Pascal

See also Delphi

Works with: Extended Pascal
program topAndTail(output);
var
	line: string(20);
begin
	line := 'ABCDEF';
	
	if length(line) > 1 then
	begin
		{ string with first character removed }
		writeLn(subStr(line, 2));
		{ index range expression: only possible for strings }
		{ _not_ designated `bindable` [e.g. `bindable string(20)`] }
		writeLn(line[2..length(line)]);
		
		{ string with last character removed }
		
		writeLn(subStr(line, 1, length(line) - 1));
		{ only legal with non-bindable strings: }
		writeLn(line[1..length(line)-1])
	end;
	
	{ string with both the first and last characters removed }
	if length(line) > 2 then
	begin
		writeLn(subStr(line, 2, length(line) - 2));
		{ only for non-bindable strings: }
		writeLn(line[2..length(line)-1])
	end
end.

It is imperative that firstCharacterIndex + substringLength specified to subStr(source, firstCharacterIndex, substringLength) must be valid index in source. Therefore you need to perform checks beforehand.

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

In perl, we can also remove the last character from a string variable with the chop function:

$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

Phix

Library: Phix/basics
constant s = "(test)"
?s[2..-1]
?s[1..-2]
?s[2..-2]
Output:
"test)"
"(test"
"test"

Phixmonti

include ..\Utilitys.pmt

"(test)"
dup 1 del ?
dup -1 del ?
dup 1 del -1 del ?

Or...

include ..\Utilitys.pmt

"(test)"
len 1 - 2 swap slice ?
len 1 - 1 swap slice ?
len 2 - 2 swap slice ?

PHP

<?php
echo substr("knight", 1), "\n";       // strip first character
echo substr("socks", 0, -1), "\n";    // strip last character
echo substr("brooms", 1, -1), "\n";   // strip both first and last characters
?>

Picat

Functions

go =>
  test("upraisers"),
  test("Δημοτική"),
  nl.

test(S) =>
  println(s=S),
  println(butfirst=S.slice(2)),
  println(butfirst=S.tail),
  println(butfirst=S[2..S.len]),  
  
  println(butlast=S.but_last()),
  
  println(butfirst_butlast=S.tail.but_last),
  println(butfirst_butlast=slice(S,2,S.length-1)),
  println(butfirst_butlast=[S[I] : I in 2..S.length-1]),
  println(butfirst_butlast=S[2..S.length-1]),  
  nl.

but_last(S)  = S.slice(1,S.length-1).
Output:
s = upraisers
butfirst = praisers
butfirst = praisers
butfirst = praisers
butlast = upraiser
butfirst_butlast = praiser
butfirst_butlast = praiser
butfirst_butlast = praiser
butfirst_butlast = praiser

s = Δημοτική
butfirst = ημοτική
butfirst = ημοτική
butfirst = ημοτική
butlast = Δημοτικ
butfirst_butlast = ημοτικ
butfirst_butlast = ημοτικ
butfirst_butlast = ημοτικ
butfirst_butlast = ημοτικ

Using append/3

Translation of: Prolog
go2 =>
  test2("upraisers"),
  nl,
  test2("Δημοτική"),
  nl.

test2(L) :-
    L = [_|L1],
    remove_last(L, L2),
    remove_last(L1, L3),
    writef("Original string          : %s\n", L),
    writef("Without first char       : %s\n", L1),
    writef("Without last char        : %s\n", L2),
    writef("Without first/last chars : %s\n", L3).
 
remove_last(L, LR) :-
    append(LR, [_], L).
Output:
Original string          : upraisers
Without first char       : praisers
Without last char        : upraiser
Without first/last chars : praiser

Original string          : Δημοτική
Without first char       : ημοτική
Without last char        : Δημοτικ
Without first/last chars : ημοτικ

PicoLisp

: (pack (cdr (chop "knight")))         # Remove first character
-> "night"

: (pack (head -1 (chop "socks")))      # Remove last character
-> "sock"

: (pack (cddr (rot (chop "brooms"))))  # Remove first and last characters
-> "room"

PL/I

declare s character (100) varying;
s = 'now is the time to come to the aid of the party';
if length(s) <= 2 then stop;
put skip list ('First character removed=' || substr(s,2) );
put skip list ('Last character removed='  || substr(s, 1, length(s)-1) );
put skip list ('One character from each end removed=' ||
   substr(s, 2, length(s)-2) );

OUTPUT:

First character removed=ow is the time to come to the aid of the party
Last character removed=now is the time to come to the aid of the part 
One character from each end removed=ow is the time to come to the aid of the part 

Plain English

To run:
Start up.
Demonstrate removing the first and last characters from "Rosetta Code".
Wait for the escape key.
Shut down.

To demonstrate removing the first and last characters from a string:
Slap a substring on the string.
Add 1 to the substring's first.
Write the substring on the console.
Subtract 1 from the substring's first.
Subtract 1 from the substring's last.
Write the substring on the console.
Add 1 to the substring's first.
Write the substring on the console.
Output:
osetta Code
Rosetta Cod
osetta Cod

PowerShell

Works with: PowerShell version 4.0

First method

$string = "top and tail"
$string
$string.Substring(1)
$string.Substring(0, $string.Length - 1)
$string.Substring(1, $string.Length - 2)

Second method

$string = "top and tail"
$string
$string[1..($string.Length - 1)] -join ""
$string[0..($string.Length - 2)] -join ""
$string[1..($string.Length - 2)] -join ""

Output:

top and tail
op and tail
top and tai
op and tai

Prolog

Works with SWI-Prolog.

remove_first_last_chars :-
    L = "Rosetta",
    L = [_|L1],
    remove_last(L, L2),
    remove_last(L1, L3),
    writef('Original string      : %s\n', [L]),
    writef('Without first char       : %s\n', [L1]),
    writef('Without last char        : %s\n', [L2]),
    writef('Without first/last chars : %s\n', [L3]).

remove_last(L, LR) :-
    append(LR, [_], L).

Output :

 ?- remove_first_last_chars.
Original string          : Rosetta
Without first char       : osetta
Without last char        : Rosett
Without first/last chars : osett
true.

PureBasic

If OpenConsole()  
  PrintN(Right("knight", Len("knight") - 1))  ;strip the first letter
  PrintN(Left("socks", Len("socks")- 1))      ;strip the last letter
  PrintN(Mid("brooms", 2, Len("brooms") - 2)) ;strip both the first and last letter
  
  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
  CloseConsole()
EndIf

Sample output:

night
sock
room

Python

print "knight"[1:]     # strip first character
print "socks"[:-1]     # strip last character
print "brooms"[1:-1]   # strip both first and last characters


Or, composing atomic functional expressions for these slices:

from functools import (reduce)


def main():
    for xs in transpose(
        (chunksOf(3)(
            ap([tail, init, compose(init)(tail)])(
                ['knights', 'socks', 'brooms']
            )
        ))
    ):
        print(xs)


# GENERIC -------------------------------------------------

# tail :: [a] -> [a]
def tail(xs):
    return xs[1:]


# init::[a] - > [a]
def init(xs):
    return xs[:-1]


# ap (<*>) :: [(a -> b)] -> [a] -> [b]
def ap(fs):
    return lambda xs: reduce(
        lambda a, f: a + reduce(
            lambda a, x: a + [f(x)], xs, []
        ), fs, []
    )


# chunksOf :: Int -> [a] -> [[a]]
def chunksOf(n):
    return lambda xs: reduce(
        lambda a, i: a + [xs[i:n + i]],
        range(0, len(xs), n), []
    ) if 0 < n else []


# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
    return lambda f: lambda x: g(f(x))


# transpose :: [[a]] -> [[a]]
def transpose(xs):
    return list(map(list, zip(*xs)))


if __name__ == '__main__':
    main()
Output:
['nights', 'knight', 'night']
['ocks', 'sock', 'ock']
['rooms', 'broom', 'room']

Quackery

As a dialogue in the Quackery shell.

/O> $ "callipygian"
... say "original string:   "
... dup echo$ cr
... say "without head:      "
... dup behead drop echo$ cr
... say "without tail:      "
... -1 split drop dup echo$ cr
... say "topped and tailed: "
... behead drop echo$ cr
... 
original string:   callipygian
without head:      allipygian
without tail:      callipygia
topped and tailed: allipygia

Racket

#lang racket

(define str "ストリング")

(substring str 1)
(substring str 0 (sub1 (string-length str)))
(substring str 1 (sub1 (string-length str)))

Output:

"トリング"
"ストリン"
"トリン"

Raku

(formerly Perl 6)

Raku provides both functional and method forms of substr. Note that, unlike in Perl 5, offsets from the end do not use negative numbers, but instead require a function expressing the negative offset relative to the length parameter, which is supplied by the operator. The form *-1 is just a simple way to write such a function.

We use musical sharps and flats to illustrate that Raku is comfortable with characters from any Unicode plane.

my $s = '𝄪♯♮♭𝄫';

print qq:to/END/;
    Original:
    $s

    Remove first character:
    { substr($s, 1) }
    { $s.substr(1) }

    Remove last character:
    { substr($s, 0, *-1) }
    { $s.substr( 0, *-1) }
    { $s.chop }

    Remove first and last characters:
    { substr($s, 1, *-1) }
    { $s.substr(1, *-1) }
    END
Output:
Original:
𝄪♯♮♭𝄫

Remove first character:
♯♮♭𝄫
♯♮♭𝄫
 
Remove last character:
𝄪♯♮♭
𝄪♯♮♭
𝄪♯♮♭
 
Remove first and last characters:
♯♮♭
♯♮♭

Raven

define println use $s
   $s print "\n" print

"0123456789" as $str

define offTheTop use $s
   $s 1 0x7FFFFFFF extract

define offTheTail use $s
   $s 0 -1 extract


$str offTheTop  println
$str offTheTail println
$str offTheTop  offTheTail  println
Output:
123456789
012345678
12345678

REXX

error prone

This REXX version is error prone in that if the string is less than two characters, then the   left   and/or   substr   BIFs will fail   (because of an invalid length specified).

/*REXX program demonstrates removal of  1st/last/1st-and-last  characters from a string.*/
@ = 'abcdefghijk'
say '                  the original string ='  @
say 'string first        character removed ='  substr(@, 2)
say 'string         last character removed ='  left(@, length(@) -1)
say 'string first & last character removed ='  substr(@, 2, length(@) -2)
                                                 /*stick a fork in it,  we're all done. */
   /* ╔═══════════════════════════════════════════════════════════════════════════════╗
      ║  However, the original string may be null or exactly one byte in length which ║
      ║  will cause the  BIFs to fail because of  either zero  or  a negative length. ║
      ╚═══════════════════════════════════════════════════════════════════════════════╝ */

output

                  the original string = abcdefghijk
string first        character removed = bcdefghijk
string         last character removed = abcdefghij
string first & last character removed = bcdefghij

robust version

This REXX version correctly handles a string of zero (null) or one byte.

/*REXX program demonstrates removal of  1st/last/1st-and-last  characters from a string.*/
@ = 'abcdefghijk'
say '                  the original string ='  @
say 'string first        character removed ='  substr(@, 2)
say 'string         last character removed ='  left(@, max(0, length(@) -1))
say 'string first & last character removed ='  substr(@, 2, max(0, length(@) -2))
exit                                             /*stick a fork in it,  we're all done. */

                              /* [↓]  an easier to read version using a length variable.*/
@ = 'abcdefghijk'
L=length(@)
say '                  the original string ='  @
say 'string first        character removed ='  substr(@, 2)
say 'string         last character removed ='  left(@, max(0, L-1) )
say 'string first & last character removed ='  substr(@, 2, max(0, L-2) )

output   is the same as the 1st REXX version.

faster version

This REXX version is faster   (uses   parse   instead of multiple BIFs).

/*REXX program demonstrates removal of  1st/last/1st-and-last  characters from a string.*/
@ = 'abcdefghijk'
say '                  the original string =' @

parse var @ 2 z
say 'string first        character removed =' z

m=length(@) - 1
parse var @ z +(m)
say 'string         last character removed =' z

n=length(@) - 2
parse var @ 2 z +(n)
if n==0  then z=                                /*handle special case of a length of 2.*/
say 'string first & last character removed =' z /*stick a fork in it,  we're all done. */

output   is the same as the 1st REXX version.

Ring

aString = "1Welcome to the Ring Programming Language2"
see substr(aString,2,len(aString)-1) + nl +
substr(aString,1,len(aString)-1) + nl +
substr(aString,2,len(aString)-2) + nl

RPL

Basic RPL:

"Knight" 2 OVER SIZE SUB
"Socks" 1 OVER SIZE 1 - SUB
"Brooms" 2 OVER SIZE 1 - SUB

From HP-48 versions, one can also do this way:

"Knight" TAIL
"Socks" REVLIST TAIL REVLIST
"Brooms" TAIL REVLIST TAIL REVLIST
Output:
3: night
2: Sock
1: room

Ruby

puts "knight"[1..-1]   # strip first character
puts "socks"[0..-2]    # strip last character
puts "socks".chop      # alternate way to strip last character
puts "brooms"[1..-2]   # strip both first and last characters
puts "与今令"[1..-2]    # => 今

Run BASIC

s$  = "Run BASIC"
print mid$(s$,2)             'strip first
print left$(s$,len(s$) -1)   'strip last
print mid$(s$,2,len(s$) -2)  'strip first and last

Rust

One possibility is to modify the owned string representation:

fn main() {
    let s = String::from("žluťoučký kůň");

    let mut modified = s.clone();
    modified.remove(0);
    println!("{}", modified);

    let mut modified = s.clone();
    modified.pop();
    println!("{}", modified);

    let mut modified = s;
    modified.remove(0);
    modified.pop();
    println!("{}", modified);
}

Another possibility is to cut a string slice (moreover, this version assumes nothing about the string length):

fn main() {
    let s = "žluťoučký kůň";

    println!(
        "{}",
        s.char_indices()
            .nth(1)
            .map(|(i, _)| &s[i..])
            .unwrap_or_default()
    );

    println!(
        "{}",
        s.char_indices()
            .nth_back(0)
            .map(|(i, _)| &s[..i])
            .unwrap_or_default()
    );

    println!(
        "{}",
        s.char_indices()
            .nth(1)
            .and_then(|(i, _)| s.char_indices().nth_back(0).map(|(j, _)| i..j))
            .map(|range| &s[range])
            .unwrap_or_default()
    );
}

Scala

Library: Scala
println("knight".tail)               // strip first character
println("socks".init)         // strip last character
println("brooms".tail.init)   // strip both first and last characters

Scheme

(define (string-top s)
  (if (string=? s "") s (substring s 0 (- (string-length s) 1))))

(define (string-tail s)
  (if (string=? s "") s (substring s 1 (string-length s))))

(define (string-top-tail s)
  (string-tail (string-top s)))

sed

Remove the first character:

s/.//

Remove the last character:

s/.$//

Remove the first and the last character in one step (a bit more complex, to correctly handle single-character strings):

s/.\(\(.*\).\)\{0,1\}/\2/

Seed7

$ include "seed7_05.s7i";

const proc: main is func
  local
    const string: stri is "upraisers";
  begin
    writeln("Full string:   " <& stri);
    writeln("Without first: " <& stri[2 ..]);
    writeln("Without last:  " <& stri[.. pred(length(stri))]);
    writeln("Without both:  " <& stri[2 .. pred(length(stri))]);
  end func;

Output:

Full string:   upraisers
Without first: praisers
Without last:  upraiser
Without both:  praiser

SenseTalk

set message to peaceSymbol & "Peace!"
put message
put characters second to last of message
put characters 1 to -2 of message
put the second to penultimate characters of message

Output:

☮Peace!
Peace!
☮Peace
Peace

Sidef

Strip any characters:

say "knight".substr(1);       # strip first character
say "socks".substr(0, -1);    # strip last character
say "brooms".substr(1, -1);   # strip both first and last characters
say "与今令".substr(1, -1);    # => 今
Output:
night
sock
room
今

Strip graphemes:

var gstr = "J\x{332}o\x{332}s\x{332}e\x{301}\x{332}";
say gstr-/^\X/;                    # strip first grapheme
say gstr-/\X\z/;                   # strip last grapheme
say gstr.sub(/^\X/).sub(/\X\z/);   # strip both first and last graphemes
Output:
o̲s̲é̲
J̲o̲s̲
o̲s̲

Smalltalk

Works with: GNU Smalltalk

These all use built-in collection methods that will work with any kind of ordered collection, not just Strings. There is no error checking. They will fail if the string is not at least two characters long.

s := 'upraisers'.
Transcript show: 'Top: ', s allButLast; nl. 
Transcript show: 'Tail: ', s allButFirst; nl.   
Transcript show: 'Without both: ', s allButFirst allButLast; nl.    
Transcript show: 'Without both using substring method: ', (s copyFrom: 2 to: s size - 1); nl.
Output:
Top: upraiser                                                                                                                           
Tail: praisers                                                                                                                          
Without both: praiser                                                                                                                   
Without both using substring method: praiser 

SNOBOL4

     "knight" len(1) rem . output       ;* strip first character
     "socks" rtab(1) . output           ;* strip last character
     "brooms" len(1) rtab(1) . output   ;* strip both first and last characters

Standard ML

- val str = "abcde";
val str = "abcde" : string
- String.substring(str, 1, String.size str - 1);
val it = "bcde" : string
- String.substring(str, 0, String.size str - 1);
val it = "abcd" : string
- String.substring(str, 1, String.size str - 2);
val it = "bcd" : string

Swift

Swift strings are native Unicode strings and do not index through the code points. Swift's String.Index refers to true Unicode characters (Unicode grapheme clusters). Swift standard library has generic functionality that not only works with strings, but also with any type that conforms to relevant protocols. The first method presented here uses generic functions from Swift standard library:

let txt = "0123456789"
println(dropFirst(txt))
println(dropLast(txt))
println(dropFirst(dropLast(txt)))
Output:
123456789
012345678
12345678

The other method is slicing by range subscripting:

let txt = "0123456789"
println(txt[txt.startIndex.successor() ..< txt.endIndex])
println(txt[txt.startIndex             ..< txt.endIndex.predecessor()])
println(txt[txt.startIndex.successor() ..< txt.endIndex.predecessor()])
Output:
123456789
012345678
12345678

Another way is mutating the string:

var txt = "0123456789"
txt.removeAtIndex(txt.startIndex)
txt.removeAtIndex(txt.endIndex.predecessor())

The above functions return what they remove. You can also extend String type and define BASIC-style functions:

extension String {
    
    /// Ensure positive indexes
    
    private func positive(index: Int) -> Int {
        
        if index >= 0 { return index }
        
        return count(self) + index
    }
    
    /// Unicode character by zero-based integer (character) `index`
    /// Supports negative character index to count from end. (-1 returns character before last)
    
    subscript(index: Int) -> Character {
        
        return self[advance(startIndex, positive(index))]
    }
    
    /// String slice by character index
    
    subscript(range: Range<Int>) -> String {
        
        return self[advance(startIndex, range.startIndex) ..<
                    advance(startIndex, range.endIndex, endIndex)]
    }
    
    /// Left portion of text to `index`
    
    func left(index : Int) -> String {
        
        return self[0 ..< positive(index)]
    }
    
    /// Right portion of text from `index`
    
    func right(index : Int) -> String{
        
        return self[positive(index) ..< count(self)]
    }
    
    /// From `start` index until `end` index
    
    func mid(start: Int, _ end: Int) -> String {
        
        return self[positive(start) ..< positive(end)]
    }
    
}

let txt = "0123456789"

txt.right(1) // Right part without first character
txt.left(-1) // Left part without last character
txt.mid(1,-1) // Middle part without first and last character

Tcl

puts [string range "knight" 1 end];       # strip first character
puts [string range "write" 0 end-1];        # strip last character
puts [string range "brooms" 1 end-1];       # strip both first and last characters

TorqueScript

String with first character removed

 %string = "Moo";
 %string = getSubStr(%string, 1, strLen(%string) - 1);
 echo(%string);

String with last character removed

 %string = "Moo";
 %string = getSubStr(%string, 0, strLen(%string) - 1);
 echo(%string);

String with both the first and last characters removed

 %string = "Moo";
 %string = getSubStr(%string, 1, strLen(%string) - 2);
 echo(%string);


Output:

 oo
 Mo
 o

TUSCRIPT

$$ MODE TUSCRIPT
str="upraisers"
str1=EXTRACT (str,2,0)
str2=EXTRACT (str,0,-1)
str3=EXTRACT (str,2,-1)
PRINT str
PRINT str1
PRINT str2
PRINT str3

Output:

upraisers
praisers
upraiser
upraiser 

UNIX Shell

First or last character:

str='abcdefg'
echo "${str#?}"   # Remove first char
echo "${str%?}"   # Remove last char

First and last character:

Only zsh supports nested string manipulation.
echo ${${str#?}%?}   # Remove first & last chars
bash and ksh, use substring expansion, from character index 1 for length of (string length) minus 2
echo "${s:1:${#s}-2}"
POSIX shells like dash, need a temp variable
tmp=${s#?}; tmp=${tmp%?}; echo "$tmp"

Vala

// declare test string
string s = "Hello, world!";
// remove first letter
string s_first = s[1:s.length];
//remove last letter
string s_last = s[0:s.length - 1];
// remove first and last letters
string s_first_last = s[1:s.length - 1];

VBScript

Function TopNTail(s,mode)
    Select Case mode
        Case "top"
            TopNTail = Mid(s,2,Len(s)-1)
        Case "tail"
            TopNTail = Mid(s,1,Len(s)-1)
        Case "both"
            TopNTail = Mid(s,2,Len(s)-2)
    End Select
End Function

WScript.Echo "Top: UPRAISERS = " & TopNTail("UPRAISERS","top")
WScript.Echo "Tail: UPRAISERS = " & TopNTail("UPRAISERS","tail")
WScript.Echo "Both: UPRAISERS = " & TopNTail("UPRAISERS","both")
Output:
Top: UPRAISERS = PRAISERS
Tail: UPRAISERS = UPRAISER
Both: UPRAISERS = PRAISER

Wren

Library: Wren-str

As Wren's string slicing and other built-in methods generally work at the byte level, we use the above module for this task which works at the code-point level.

import "./str" for Str

var a = "Beyoncé"
var b = Str.delete(a, 0)
var len = a.codePoints.count
var c = Str.delete(a, len-1)
var d = Str.delete(c, 0)
for (e in [a, b, c, d]) System.print(e)
Output:
Beyoncé
eyoncé
Beyonc
eyonc

XPL0

include c:\cxpl\stdlib;
char S, P;
[S:= "Smiles";
Text(0, S+1);           \first character removed
CrLf(0);
P:= S + StrLen(S) - 2;  \point to last character in string
P(0):= P(0) ! $80;      \set the MSb on the last character
Text(0, S);             \last character removed
CrLf(0);
Text(0, S+1);           \first and last characters removed
CrLf(0);
]

Output:

miles
Smile
mile

zkl

"Smiles"[1,*]  //-->miles
"Smiles"[0,-1] //-->Smile
"Smiles"[1,-1] //-->mile

[] format is [offset (zero based), length]. * means "to the end", a negative number means from the end.

ZX Spectrum Basic

10 PRINT FN f$("knight"): REM strip the first letter. You can also write PRINT "knight"(2 TO)
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$))