Substring/Top and tail: Difference between revisions
m
→{{header|EasyLang}}
(21 intermediate revisions by 13 users not shown) | |||
Line 23:
{{trans|Python}}
<
print(‘socks’[0 .< (len)-1])
print(‘brooms’[1 .< (len)-1])</
{{out}}
Line 35:
=={{header|360 Assembly}}==
<
SUBSTRTT CSECT
USING SUBSTRTT,R13 base register
Line 61:
S6 DS CL6
YREGS
END SUBSTRTT</
{{out}}
<pre>
Line 71:
=={{header|ACL2}}==
<
(coerce (rest (coerce str 'list)) 'string))
Line 85:
(str-rdc "string")
(str-rest "string")
(str-rest (str-rdc "string"))</
=={{header|Action!}}==
<
CHAR ARRAY text="qwertyuiop"
CHAR ARRAY res(20)
Line 103:
SCopyS(res,text,2,text(0)-1)
PrintF("String without the top and the tail:%E ""%S""%E%E",res)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Top_and_tail.png Screenshot from Atari 8-bit computer]
Line 122:
=={{header|Ada}}==
<
procedure Remove_Characters is
Line 132:
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:
Line 143:
With UTF8 support in Ada 2012 (Wide_Character of literals is automatic):
<
with Ada.Strings.UTF_Encoding.Wide_Strings;
Line 175:
("Without_Both: """ & U (U'First + 1 .. U'Last - 1) & """"));
end Remove_Characters;</
Output:
Line 185:
=={{header|Aime}}==
<
o_newline();
o_text(delete("knights", -1));
o_newline();
o_text(delete(delete("knights", 0), -1));
o_newline();</
{{out}}
<pre>nights
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].}}
{{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''.}}
<
STRING str="upraisers";
Line 214:
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:
<pre>
Line 229:
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
#include <hopper.h>
#proto showmessage(_X_)
Line 244:
{_S_,"\n"}print
back
</syntaxhighlight>
{{out}}
<pre>
Line 253:
=={{header|Apex}}==
<
String strOrig = 'brooms';
String str1 = strOrig.substring(1, strOrig.length());
Line 270:
String str3 = strOrig.replaceAll( '^.|.$', '' );
system.debug(str3);
</syntaxhighlight>
{{out}}
Line 283:
=={{header|AppleScript}}==
<
set stringLength to (count aString) -- The number of characters in the text.
Line 311:
end if
return substring1 & linefeed & substring2 & linefeed & substring3</
{{output}}
Line 320:
=={{header|Arturo}}==
<
socks: "socks"
brooms: "brooms"
print drop knight.
print slice knight 1 (size knight)-1 ; alternate way to strip first character
Line 331:
print slice socks 0 (size socks)-2 ; yet another way to strip last character
print chop drop brooms
print slice brooms 1 (size brooms)-2 ; alternate way to strip both first and last characters</
{{out}}
Line 345:
=={{header|AutoHotkey}}==
<
MsgBox % SubStr(MyString, 2)
MsgBox % SubStr(MyString, 1, StrLen(MyString)-1)
MsgBox % SubStr(MyString, 2, StrLen(MyString)-2)</
=={{header|AWK}}==
<
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
}</
=={{header|BASIC}}==
<
20 PRINT FN L$("SOCKS"): REM STRIP THE LAST LETTER
30 PRINT FN B$("BROOMS"): REM STRIP BOTH THE FIRST AND LAST LETTER
Line 366:
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$))</
==={{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}}===
<
110 PRINT S$(2:)
120 PRINT S$(:LEN(S$)-1)
130 PRINT S$(2:LEN(S$)-1)</
==={{header|Sinclair ZX81 BASIC}}===
Note that strings are indexed from 1.
<
20 LET S$="KNIGHTS"
30 REM WITH FIRST CHARACTER REMOVED:
Line 383 ⟶ 458:
60 PRINT S$( TO LEN S$-1)
70 REM WITH BOTH REMOVED:
80 PRINT S$(2 TO LEN S$-1)</
{{out}}
<pre>NIGHTS
KNIGHT
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.
<
"substring"
1↓str
Line 399 ⟶ 489:
"substrin"
1↓¯1↓str
"ubstrin"</
=={{header|BBC BASIC}}==
<
PRINT MID$(s$, 2)
PRINT LEFT$(s$)
PRINT LEFT$(MID$(s$, 2))</
=={{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.
<
@( Δημοτική
: (%?a&utf$!a) ?"String with first character removed"
Line 429 ⟶ 519:
$ ( "String with both the first and last characters removed:"
!"String with both the first and last characters removed"
));</
<pre>!substringUTF-8
Line 438 ⟶ 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.
<
@("8-bit string":%@ ?"String with first character removed")
& @("8-bit string":?"String with last character removed" @)
Line 451 ⟶ 541:
$ ( "String with both the first and last characters removed:"
!"String with both the first and last characters removed"
));</
<pre>!substring-8-bit
Line 459 ⟶ 549:
=={{header|Burlesque}}==
<
blsq ) "RosettaCode"[-
"osettaCode"
Line 470 ⟶ 560:
blsq ) "RosettaCode"~-
"osettaCod"
</syntaxhighlight>
=={{header|C}}==
<
#include <stdlib.h>
#include <stdio.h>
Line 497 ⟶ 587:
return 0;
}</
Result:
Line 507 ⟶ 597:
=={{header|C sharp}}==
<
using System;
Line 520 ⟶ 610:
}
}
</syntaxhighlight>
Result:
Line 528 ⟶ 618:
=={{header|C++}}==
<
#include <iostream>
Line 537 ⟶ 627:
std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ;
return 0 ;
}</
Output:
<PRE>Without first letter: remier League !
Line 545 ⟶ 635:
=={{header|Clojure}}==
<
user=> (subs "knight" 1)
"night"
Line 559 ⟶ 649:
"sock"
user=> (apply str (rest (drop-last "brooms")))
"room"</
=={{header|COBOL}}==
<
program-id. toptail.
Line 578 ⟶ 668:
display data-field(2:length of data-field - 2)
goback.
end program toptail.</
{{out}}
Line 589 ⟶ 679:
=={{header|Common Lisp}}==
<code>subseq</code> will signal an error if you provide invalid start or end values.
<
*STR*
> (subseq *str* 1) ; remove first character
Line 596 ⟶ 686:
"∀Ꮺ✤Л"
> (subseq *str* 1 (1- (length *str*))) ; remove first and last character
"Ꮺ✤Л"</
=={{header|D}}==
Version for ASCII strings or Unicode dstrings:
<
void main() {
Line 611 ⟶ 701:
// strip both first and last characters
writeln("brooms"[1 .. $ - 1]);
}</
{{out}}
<pre>night
sock
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}}==
<
{$APPTYPE CONSOLE}
Line 631 ⟶ 731:
Readln;
end.</
=={{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}}==
<
int main()
Line 651 ⟶ 765:
Log( '%@', s[1 .. s.length-2] ) // strip both first and last characters
return 0</
Output:<pre>
Line 661 ⟶ 775:
=={{header|Elena}}==
ELENA 4.x :
<
public program()
Line 670 ⟶ 784:
console.printLine(testString.Substring(0, testString.Length - 1));
console.printLine(testString.Substring(1, testString.Length - 2))
}</
{{out}}
<pre>
Line 679 ⟶ 793:
=={{header|Elixir}}==
<
"abcdefg"
iex(2)> String.slice(str, 1..-1)
Line 686 ⟶ 800:
"abcdef"
iex(4)> String.slice(str, 1..-2)
"bcdef"</
=={{header|Emacs Lisp}}==
<
(substring string 1) ;=> "op and tail"
(substring string 0 (1- (length string))) ;=> "top and tai"
(substring string 1 (1- (length string)))) ;=> "op and tai"</
=={{header|Erlang}}==
<
"Hello"
2> string:sub_string(Str, 2). % To strip the string from the right by 1
Line 702 ⟶ 816:
"Hell"
4> string:sub_string(Str, 2, length(Str)-1). % To strip the string from both sides by 1
"ell"</
=={{header|Euphoria}}==
<
return s[2..$]
end function
Line 719 ⟶ 833:
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</
=={{header|F_Sharp|F#}}==
<
let main args =
let s = "一二三四五六七八九十"
Line 728 ⟶ 842:
printfn "%A" (s.Substring(0, s.Length - 1))
printfn "%A" (s.Substring(1, s.Length - 2))
0</
Output
<pre>"二三四五六七八九十"
Line 735 ⟶ 849:
=={{header|Factor}}==
<
"Rosetta code" [ rest ] [ but-last ] [ rest but-last ] tri
[ print ] tri@</
{{out}}
<pre>
Line 748 ⟶ 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.
<
s" Hello" ;
Line 755 ⟶ 869:
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.
=={{header|Fortran}}==
<
character(len=5) :: string
Line 770 ⟶ 884:
write (*,*) string(2:len(string)-1)
end program substring</
=={{header|FreeBASIC}}==
<
Dim s As String = "panda"
Line 783 ⟶ 897:
Print s2
Print s3
Sleep</
{{out}}
Line 792 ⟶ 906:
and
</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}}==
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.
<
import (
Line 817 ⟶ 959:
fmt.Println("Last rune removed: ", u[:len(u)-sizeLast])
fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast])
}</
Output:
<pre>
Line 828 ⟶ 970:
Last rune 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>
=={{header|Groovy}}==
Solution:
<
def tail = { it.size() > 1 ? it[1..-1] : '' }</
Test:
<
println """
original: ${testVal}
Line 842 ⟶ 998:
tail: ${tail(testVal)}
top&tail: ${tail(top(testVal))}
"""</
Output:
Line 851 ⟶ 1,007:
=={{header|GW-BASIC}}==
<
20 PRINT MID$(A$,2)
30 PRINT LEFT$(B$,LEN(B$)-1)
40 PRINT MID$(C$,2,LEN(C$)-2)</
=={{header|Haskell}}==
<
-- short for the particular operation.
Line 874 ⟶ 1,030:
main = do
let s = "Some string."
mapM_ (\f -> putStrLn . f $ s) [remFirst, remLast, remBoth]</
Alternative solution with builtin functions:
<
main = do
Line 894 ⟶ 1,050:
-- You can combine functions using `.`,
-- which is pronounced "compose" or "of"
middle = init . tail</
In short:
<
main = mapM_ print $ [tail, init, init . tail] <*> ["knights"]</
{{Out}}
<pre>"nights"
Line 906 ⟶ 1,062:
=={{header|Icon}} and {{header|Unicon}}==
The task is accomplished by sub-stringing.
<
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.
<
=={{header|J}}==
Line 919 ⟶ 1,075:
'''Example use:'''<br>
<
night
}: 'socks' NB. drop last item
sock
}: }. 'brooms' NB. drop first and last items
room</
=={{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, but work correctly with all Unicode code points, not just those in the Basic Multilingual Plane.
<
public static void main( String[] args ){
System.out.println( "knight".substring( 1 ) );
Line 942 ⟶ 1,098:
// then do this using a regular expressions
}
}</
Results:
Line 952 ⟶ 1,108:
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.
<syntaxhighlight lang="java">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);
}
}</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("brooms".slice(1, -1)); // strip both first and last characters</
=={{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}}==
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]' => "一二三四五六七八九"
Line 966 ⟶ 1,159:
"a"[1:-1] # => ""
</syntaxhighlight>
Recent versions of jq also have regular expression support, with named captures. This leads to many other possibilities, e.g.<
=={{header|Julia}}==
<
"y String"
Line 977 ⟶ 1,170:
julia> "My String"[2:end-1] # without first and last characters
"y Strin"</
=={{header|K}}==
K provides the system function <code>_di</code> to delete an element at
a specified index. The following code is implemented using this feature.
<syntaxhighlight lang="k">
s: "1234567890"
"1234567890"
Line 991 ⟶ 1,184:
(s _di -1+#s) _di 0 /String with both 1st and last character removed
"23456789"
</syntaxhighlight>
Another way to implement without using the above system function:
<syntaxhighlight lang="k">
s: "1234567890"
"1234567890"
Line 1,002 ⟶ 1,195:
1 - -1 _ s /Delete 1st and last character
"23456789"
</syntaxhighlight>
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
val s = "Rosetta"
Line 1,011 ⟶ 1,204:
println(s.dropLast(1))
println(s.drop(1).dropLast(1))
}</
{{out}}
Line 1,021 ⟶ 1,214:
=={{header|Lambdatalk}}==
<
{def R rosetta} -> rosetta
Line 1,040 ⟶ 1,233:
{W.rest {W.reverse {W.rest {W.reverse {J}}}}} -> トリン
</syntaxhighlight>
=={{header|Lasso}}==
<
// String with first character removed
Line 1,053 ⟶ 1,246:
// String with both the first and last characters removed
string_remove(string_remove(#str,-startposition=#str->size,-endposition=#str->size),-startposition=1,-endposition=1)</
{{out}}
<pre>he quick grey rhino jumped over the lazy green fox.
Line 1,059 ⟶ 1,252:
he quick grey rhino jumped over the lazy green fox</pre>
<
#mystring -> remove(1,1)
Line 1,068 ⟶ 1,261:
'<br />'
#mystring -> remove(1,1)& -> remove(#mystring -> size,1)
#mystring</
-> ÜÄÖカ
Line 1,074 ⟶ 1,267:
Ä =={{header|Lasso}}==
<
// String with first character removed
Line 1,086 ⟶ 1,279:
// 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</
=={{header|Liberty BASIC}}==
<
Print Mid$(string$, 2)
Print Left$(string$, (Len(string$) - 1))
Print Mid$(string$, 2, (Len(string$) - 2))</
=={{header|LiveCode}}==
<
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</
=={{header|Locomotive Basic}}==
<
20 PRINT MID$(a$,2)
30 PRINT LEFT$(b$,LEN(b$)-1)
40 PRINT MID$(c$,2,LEN(c$)-2)</
=={{header|Logo}}==
<
print butfirst :s
print butlast :s
print butfirst butlast :s</
=={{header|Logtalk}}==
Using atoms for representing strings:
<
:- object(top_and_tail).
Line 1,128 ⟶ 1,321:
:- end_object.
</syntaxhighlight>
Sample output:
<
| ?- top_and_tail::test('Rosetta').
String with first character cut: osetta
Line 1,136 ⟶ 1,329:
String with first and last characters cut: osett
yes
</syntaxhighlight>
=={{header|Lua}}==
<
print (string.sub("knights",1,-2)) -- remove the last character
print (string.sub("knights",2,-2)) -- remove the first and last characters</
=={{header|Maple}}==
There are several ways to do this. The first is, I think, the simplest.
<
> s[2..-1];
"ome string"
Line 1,154 ⟶ 1,347:
> s[2..-2];
"ome strin"</
The same functionality exists in the form of a procedure:
<
"ome string"
Line 1,163 ⟶ 1,356:
> substring( s, 2 .. -2 );
"ome strin"</
Furthermore, there is a slightly different version in the "StringTools" package:
<
> SubString( s, 2 .. -1 );
> SubString( s, 1 .. -1 );
Line 1,174 ⟶ 1,367:
"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.)
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
StringDrop["input string",-1]
StringTake["input string",{2,-2}]
</syntaxhighlight>
=={{header|MATLAB}} / {{header|Octave}}==
The following case will not handle UTF-8. However, Matlab supports conversion of utf-8 to utf-16 using native2unicode().
<syntaxhighlight lang="matlab">
% String with first character removed
str(2:end)
Line 1,193 ⟶ 1,386:
% String with both the first and last characters removed
str(2:end-1)
</syntaxhighlight>
=={{header|MiniScript}}==
<
print test[1:]
print test[:-1]
print test[1:-1]
</syntaxhighlight>
{{out}}
<pre>
Line 1,207 ⟶ 1,400:
his thin
</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}}==
Line 1,212 ⟶ 1,513:
'''$ssub''' ''sub-string'' takes string, position (zero-relative), length arguments.
<syntaxhighlight lang="actionscript">/**
Subtring/Top-Tail in Neko
*/
Line 1,222 ⟶ 1,523:
$print($ssub(data, 1, len - 1), "\n")
$print($ssub(data, 0, len - 1), "\n")
$print($ssub(data, 1, len - 2), "\n")</
{{out}}
Line 1,233 ⟶ 1,534:
=={{header|Nemerle}}==
<
using System.Console;
Line 1,247 ⟶ 1,548:
WriteLine($"$str -> $beg -> $end -> $both");
}
}</
=={{header|NetRexx}}==
<
* 02.08.2013 Walter Pachl translated from REXX
**********************************************************************/
Line 1,261 ⟶ 1,562:
End
If l>=2 Then
Say 'string first & last character removed =' z.substr(2,l-2)</
=={{header|NewLISP}}==
<
;; strip first char
(println (1 str))
Line 1,270 ⟶ 1,571:
(println (0 -1 str))
;; strip both first and last characters
(println (1 -1 str)))</
=={{header|Nim}}==
<
let s = "Hänsel ««: 10,00€"
Line 1,282 ⟶ 1,583:
# Using the runes type and slices
let r = s.toRunes
echo "With first and last characters removed (other way): ", r[1 .. ^2]</
{{out}}
<pre>Original: Hänsel ««: 10,00€
Line 1,291 ⟶ 1,592:
=={{header|Objeck}}==
<
bundle Default {
class TopTail {
Line 1,302 ⟶ 1,603:
}
}
</syntaxhighlight>
=={{header|OCaml}}==
<
if str = "" then "" else
String.sub str 1 ((String.length str) - 1)
Line 1,323 ⟶ 1,624:
print_endline (strip_last_char "socks");
print_endline (strip_both_chars "brooms");
;;</
=={{header|Oforth}}==
<
s right(s size 1-) println
s left(s size 1-) println
s extract(2, s size 1- ) println ;</
{{out}}
Line 1,341 ⟶ 1,642:
=={{header|PARI/GP}}==
<
dl(s)=concat(vecextract(Vec(s),1<<(#s-1)-1));
db(s)=concat(vecextract(Vec(s),1<<(#s-1)-2));</
=={{header|Pascal}}==
''See also [[
{{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}}==
<
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:
<
$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</
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<
<span style="color: #008080;">constant</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"(test)"</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;">1</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;">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>
<!--</
{{out}}
<pre>
Line 1,377 ⟶ 1,708:
=={{header|Phixmonti}}==
<
"(test)"
dup 1 del ?
dup -1 del ?
dup 1 del -1 del ?</
Or...
<
"(test)"
len 1 - 2 swap slice ?
len 1 - 1 swap slice ?
len 2 - 2 swap slice ?</
=={{header|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
?></
=={{header|Picat}}==
<
test("upraisers"),
test("Δημοτική"),
Line 1,420 ⟶ 1,751:
nl.
but_last(S) = S.slice(1,S.length-1).</
{{out}}
Line 1,443 ⟶ 1,774:
butfirst_butlast = ημοτικ</pre>
===Using append/3===
{{trans|Prolog}}
<
test2("upraisers"),
nl,
Line 1,461 ⟶ 1,792:
remove_last(L, LR) :-
append(LR, [_], L).</
{{out}}
Line 1,473 ⟶ 1,804:
Without last char : Δημοτικ
Without first/last chars : ημοτικ</pre>
=={{header|PicoLisp}}==
<
-> "night"
Line 1,483 ⟶ 1,813:
: (pack (cddr (rot (chop "brooms")))) # Remove first and last characters
-> "room"</
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
declare s character (100) varying;
s = 'now is the time to come to the aid of the party';
Line 1,494 ⟶ 1,824:
put skip list ('One character from each end removed=' ||
substr(s, 2, length(s)-2) );
</syntaxhighlight>
OUTPUT:
<pre>
Line 1,503 ⟶ 1,833:
=={{header|Plain English}}==
<
Start up.
Demonstrate removing the first and last characters from "Rosetta Code".
Line 1,517 ⟶ 1,847:
Write the substring on the console.
Add 1 to the substring's first.
Write the substring on the console.</
{{out}}
<pre>
Line 1,528 ⟶ 1,858:
{{works with|PowerShell|4.0}}
===First method===
<syntaxhighlight lang="powershell">
$string = "top and tail"
$string
Line 1,534 ⟶ 1,864:
$string.Substring(0, $string.Length - 1)
$string.Substring(1, $string.Length - 2)
</syntaxhighlight>
===Second method===
<syntaxhighlight lang="powershell">
$string = "top and tail"
$string
Line 1,542 ⟶ 1,872:
$string[0..($string.Length - 2)] -join ""
$string[1..($string.Length - 2)] -join ""
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 1,554 ⟶ 1,884:
Works with SWI-Prolog.
<
L = "Rosetta",
L = [_|L1],
Line 1,565 ⟶ 1,895:
remove_last(L, LR) :-
append(LR, [_], L).</
Output :
<pre> ?- remove_first_last_chars.
Line 1,576 ⟶ 1,906:
=={{header|PureBasic}}==
<
PrintN(Right("knight", Len("knight") - 1)) ;strip the first letter
PrintN(Left("socks", Len("socks")- 1)) ;strip the last letter
Line 1,583 ⟶ 1,913:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
Sample output:
<pre>night
Line 1,591 ⟶ 1,921:
=={{header|Python}}==
<
print "socks"[:-1] # strip last character
print "brooms"[1:-1] # strip both first and last characters</
Or, composing atomic functional expressions for these slices:
<
Line 1,651 ⟶ 1,981:
if __name__ == '__main__':
main()</
{{Out}}
<pre>['nights', 'knight', 'night']
Line 1,679 ⟶ 2,009:
=={{header|Racket}}==
<
#lang racket
Line 1,687 ⟶ 2,017:
(substring str 0 (sub1 (string-length str)))
(substring str 1 (sub1 (string-length str)))
</syntaxhighlight>
Output:
Line 1,704 ⟶ 2,034:
We use musical sharps and flats to illustrate that Raku is comfortable with characters from any Unicode plane.
<syntaxhighlight lang="raku"
print qq:to/END/;
Line 1,722 ⟶ 2,052:
{ substr($s, 1, *-1) }
{ $s.substr(1, *-1) }
END</
{{out}}
<pre>Original:
Line 1,741 ⟶ 2,071:
=={{header|Raven}}==
<
$s print "\n" print
Line 1,755 ⟶ 2,085:
$str offTheTop println
$str offTheTail println
$str offTheTop offTheTail println</
{{out}}
<pre>123456789
Line 1,764 ⟶ 2,094:
===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).
<
@ = 'abcdefghijk'
say ' the original string =' @
Line 1,774 ⟶ 2,104:
║ 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'''
<pre>
Line 1,785 ⟶ 2,115:
===robust version===
This REXX version correctly handles a string of zero (null) or one byte.
<
@ = 'abcdefghijk'
say ' the original string =' @
Line 1,799 ⟶ 2,129:
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 1<sup>st</sup> REXX version.
===faster version===
This REXX version is faster (uses '''parse''' instead of multiple BIFs).
<
@ = 'abcdefghijk'
say ' the original string =' @
Line 1,818 ⟶ 2,148:
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 1<sup>st</sup> REXX version. <br><br>
=={{header|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
</syntaxhighlight>
=={{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}}==
<
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] # => 今</
=={{header|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</
=={{header|Rust}}==
One possibility is to modify the owned string representation:
<
let s = String::from("žluťoučký kůň");
Line 1,860 ⟶ 2,206:
modified.pop();
println!("{}", modified);
}</
Another possibility is to cut a string slice (moreover, this version assumes
nothing about the string length):
<
let s = "žluťoučký kůň";
Line 1,891 ⟶ 2,237:
.unwrap_or_default()
);
}</
=={{header|Scala}}==
{{libheader|Scala}}
<
println("socks".init) // strip last character
println("brooms".tail.init) // strip both first and last characters</
=={{header|Scheme}}==
<
(if (string=? s "") s (substring s 0 (- (string-length s) 1))))
Line 1,907 ⟶ 2,253:
(define (string-top-tail s)
(string-tail (string-top s)))</
=={{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}}==
<
const proc: main is func
Line 1,920 ⟶ 2,274:
writeln("Without last: " <& stri[.. pred(length(stri))]);
writeln("Without both: " <& stri[2 .. pred(length(stri))]);
end func;</
Output:
Line 1,931 ⟶ 2,285:
=={{header|SenseTalk}}==
<
set message to peaceSymbol & "Peace!"
put message
Line 1,937 ⟶ 2,291:
put characters 1 to -2 of message
put the second to penultimate characters of message
</syntaxhighlight>
Output:
<
☮Peace!
Peace!
☮Peace
Peace
</syntaxhighlight>
=={{header|Sidef}}==
Strip any characters:
<
say "socks".substr(0, -1); # strip last character
say "brooms".substr(1, -1); # strip both first and last characters
say "与今令".substr(1, -1); # => 今</
{{out}}
<pre>
Line 1,961 ⟶ 2,315:
Strip graphemes:
<
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</
{{out}}
<pre>
Line 1,975 ⟶ 2,329:
{{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.
Line 1,981 ⟶ 2,335:
Transcript show: 'Without both: ', s allButFirst allButLast; nl.
Transcript show: 'Without both using substring method: ', (s copyFrom: 2 to: s size - 1); nl.
</syntaxhighlight>
{{out}}
<pre>
Line 1,990 ⟶ 2,344:
=={{header|SNOBOL4}}==
<
"socks" rtab(1) . output ;* strip last character
"brooms" len(1) rtab(1) . output ;* strip both first and last characters</
=={{header|Standard ML}}==
<
val str = "abcde" : string
- String.substring(str, 1, String.size str - 1);
Line 2,002 ⟶ 2,356:
val it = "abcd" : string
- String.substring(str, 1, String.size str - 2);
val it = "bcd" : string</
=={{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:
<
println(dropFirst(txt))
println(dropLast(txt))
println(dropFirst(dropLast(txt)))</
{{out}}
<pre>123456789
Line 2,016 ⟶ 2,370:
12345678</pre>
The other method is slicing by range subscripting:
<
println(txt[txt.startIndex.successor() ..< txt.endIndex])
println(txt[txt.startIndex ..< txt.endIndex.predecessor()])
println(txt[txt.startIndex.successor() ..< txt.endIndex.predecessor()])</
{{out}}
<pre>123456789
Line 2,025 ⟶ 2,379:
12345678</pre>
Another way is mutating the string:
<
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:
<
/// Ensure positive indexes
Line 2,084 ⟶ 2,438:
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</
=={{header|Tcl}}==
<
puts [string range "write" 0 end-1]; # strip last character
puts [string range "brooms" 1 end-1]; # strip both first and last characters</
=={{header|TorqueScript}}==
Line 2,112 ⟶ 2,466:
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
str="upraisers"
Line 2,122 ⟶ 2,476:
PRINT str2
PRINT str3
</syntaxhighlight>
Output:
<pre>
Line 2,135 ⟶ 2,489:
First ''or'' last character:
<
echo "${str#?}" # Remove first char
echo "${str%?}" # Remove last char</
First ''and'' last character:
: Only zsh supports nested string manipulation.
: <
: bash and ksh, use substring expansion, from character index 1 for length of (string length) minus 2
: <
: POSIX shells like dash, need a temp variable
: <
=={{header|Vala}}==
<
// declare test string
string s = "Hello, world!";
Line 2,158 ⟶ 2,512:
// remove first and last letters
string s_first_last = s[1:s.length - 1];
</syntaxhighlight>
=={{header|VBScript}}==
<
Select Case mode
Case "top"
Line 2,174 ⟶ 2,528:
WScript.Echo "Top: UPRAISERS = " & TopNTail("UPRAISERS","top")
WScript.Echo "Tail: UPRAISERS = " & TopNTail("UPRAISERS","tail")
WScript.Echo "Both: UPRAISERS = " & TopNTail("UPRAISERS","both")</
{{out}}
Line 2,184 ⟶ 2,538:
{{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.
<
var a = "Beyoncé"
Line 2,191 ⟶ 2,545:
var c = Str.delete(a, len-1)
var d = Str.delete(c, 0)
for (e in [a, b, c, d]) System.print(e)</
{{out}}
Line 2,202 ⟶ 2,556:
=={{header|XPL0}}==
<
char S, P;
[S:= "Smiles";
Line 2,213 ⟶ 2,567:
Text(0, S+1); \first and last characters removed
CrLf(0);
]</
Output:
Line 2,223 ⟶ 2,577:
=={{header|zkl}}==
<
"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.
Line 2,231 ⟶ 2,585:
=={{header|ZX Spectrum Basic}}==
<
20 PRINT FN l$("socks"): REM strip the last letter
30 PRINT FN b$("brooms"): REM strip both the first and last letter
Line 2,238 ⟶ 2,592:
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$)) </
{{omit from|GUISS}}
|