Substring/Top and tail: Difference between revisions
m
→{{header|EasyLang}}
(Substring/Top and tail in Dart) |
|||
(7 intermediate revisions by 5 users not shown) | |||
Line 324:
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</syntaxhighlight>
Line 734:
=={{header|EasyLang}}==
<syntaxhighlight
print substr
print substr
print substr
</syntaxhighlight>
{{out}}
<pre>
Easylan
asylang
asylan
</pre>
Line 1,083:
=={{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.
<syntaxhighlight lang="java">public class RM_chars {
Line 1,107:
sock
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}}==
Line 2,136 ⟶ 2,160:
=={{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>
Line 2,510 ⟶ 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.
<syntaxhighlight lang="
var a = "Beyoncé"
|