Logo

Programming-Idioms

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

Idiom #340 Last character of string

Assign to c the value of the last character of the string s.

Explain the type of c, and what happens if s is empty.

Make sure to properly handle multi-bytes characters.

r := []rune(s)
c := r[len(r)-1]
import "unicode/utf8"
c, _ := utf8.DecodeLastRuneInString(s)
char c = s[^1];
final c = s[s.length - 1];
lastChar :: String -> Char
lastChar s
    | s=="" = ""
    | otherwise = s !! (length s - 1)
LazUtf8
function GetLastUtfCodePoint(const S: String): String;
var
  p: PChar;
  PLen: PtrInt;
begin
  Result := '';
  p := UTF8CodepointStart(PChar(S), Length(S), Utf8Length(S) - 1);
  PLen := UTF8CodepointSize(p);
  Result := p;
  SetLength(Result,PLen);
end; 

var
  s: string;
begin
  c := GetLastUtfCodePoint(s);
end.
{$modeswitch unicodestrings}
c := s[Length(s)];
c = s[-1]
c = s[-1]
let c = s.chars().last().unwrap();

New implementation...
< >
programming-idioms.org