Logo

Programming-Idioms

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.
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
char c = s[^1];
final c = s[s.length - 1];
r := []rune(s)
c := r[len(r)-1]
import "unicode/utf8"
c, _ := utf8.DecodeLastRuneInString(s)
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]