Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #47 Extract string suffix

Create string t consisting in the 5 last characters of string s.
Make sure that multibyte characters are properly handled.

The end of the string s
@import Foundation;
NSString *t=[s substringFromIndex:s.length-5];
(let [t (clojure.string/join (take-last 5 s))])
(def t 
  (when (string? s)
    (let [from (-> s (count) (- 5) (max 0))]
      (subs s from))))
IDENTIFICATION DIVISION.
PROGRAM-ID. suffix.
PROCEDURE DIVISION.
    MOVE FUNCTION LENGTH(s) TO len
    COMPUTE pos = (len - 5) + 1
    MOVE    s(pos:) TO t    	 	
STOP RUN.
#include <string>
std::string t = s.substr(s.length() - 5);
var t = s.Substring(s.Length - 5);
string t = s[$-5..$];
var n = s.length;
var t = s.substring(n-5, n);
<<_ :: binary-5>> <> t = s
t = String.slice(s, -5, 5)
[T5, T4, T3, T2, T1 | _] = lists:reverse(S),
T = [T1, T2, T3, T4, T5].
character(len=5) :: t
t = s(len(s)-4:)
t := s
r := []rune(s)
if len(r) > 5 {
	t = string(r[len(r)-5:])
}
import "unicode/utf8"
i := len(s)
for j := 0; i > 0 && j < 5; j++ {
	_, size := utf8.DecodeLastRuneInString(s[0:i])
	i -= size
}
t := s[i:]
final t = s[-5..-1]
t = drop (length s - 5) s
var t = s.slice(-5);
import static java.lang.Character.isSurrogate;
int i = s.length() - 5;
if (isSurrogate(s.charAt(i))) --i;
String t = s.substring(i);
String t = s;
if (s.length()>= 5)
	t = s.substring(s.length()-5);
val t = s.takeLast(5)
(setf *t* (subseq s (- (length s) 5)))
$t = mb_substr($s, -5, null, 'UTF-8');
Function RightStr(const AText: AnsiString; const ACount: Integer): AnsiString;
var j,l:integer;
begin
  l:=length(atext);
  j:=ACount;
  if j>l then j:=l;
  Result:=Copy(AText,l-j+1,j);
end;
use utf8;

my $t = substr($s, -5);
t = s[-5:]
t = s[-5..]
t = s[-5..-1]
let last5ch = s.chars().count() - 5;
let t: String = s.chars().skip(last5ch).collect();
use unicode_segmentation::UnicodeSegmentation;
let s = "a̐éö̲\r\n";
let t = s.grapheme_indices(true).rev().nth(5).map_or(s, |(i,_)|&s[i..]);
s last: 5
t = Right(s, 5)
t = s.Substring(s.Length - 5)

New implementation...