Posted on January 03, 2020 at 02:19 (GMT +00:00) by
Colin
Posting another new function, toNameCase, it works for some additional languages, but not all. It currently, supports some latin based languages and a subset of cyrillc. It should however be
very easy easy enough to add support for all languages (if you need this, let me know in the comments).
Usage with attribution to author.
//
// Convert a string to name case, e.g. my name -> My Name
// Author: Colin J.D. Stewart
// Usage: toNameCase( 'my name' );
//
function toNameCase(const input: string): string;
var
i: Integer;
b: boolean;
begin
b := true;
Result := input;
for i := 1 to Length(Result) do begin
if b = true then begin
case Result[i] of
'a'..'z': Result[i] := Char(Word(Result[i]) - 32);
'à'..'ö': Result[i] := Char(Word(Result[i]) - 32);
'ø'..'ÿ': Result[i] := Char(Word(Result[i]) - 34);
'ā'..'ň', 'ŋ'..'ž': Result[i] := Char(Word(Result[i]) - 1);
'а'..'я': Result[i] := Char(Word(Result[i]) - 32);
end;
if not (Result[i] in [' ', '.', ',', '-', '''']) then b := false;
end else begin
if (Result[i] in [' ', '.', ',', '-', '''']) then b := true;
end;
end;
end;
Note there is an alternative way to do this, Windows API has a function to perform
widestring uppercase etc. Both FreePascal and Delphi use this method under function
WideUpperCase, so we could do:
//
// Convert a string to name case, e.g. my name -> My Name
// Author: Colin J.D. Stewart
// Usage: toNameCaseEx( 'my name' );
//
function toNameCaseEx(const input: string): string;
var
i: Integer;
b: boolean;
begin
b := true;
Result := input;
for i := 1 to Length(Result) do begin
if b = true then begin
if not (Result[i] in [' ', '.', ',', '-', '''']) then begin
b := false;
Result[i] := WideUpperCase(Result[i])[1];
end;
end else begin
if (Result[i] in [' ', '.', ',', '-', '''']) then b := true;
end;
end;
end;
However, it does seem to have some limitations. The third option would be to make a table with mapped characters (I may look into making this method at a later data and do some various tests)
/Signing off