function lowcase(s: string): string;

Black Magic 0 Tallied Votes 251 Views Share

A simple function that converts alphabetic values into their respective lowercase value.

function lowcase(s: string): string;
var
  i: integer;
begin
  s := upcase(s);

  for i := 1 to length(s) do
  begin
    if s[i] in ['A'..'z'] then // this is to check that s[i] is alphabetic
    begin
      s[i] := chr(ord(s[i]) + 32); // convert s[i] to a numeric value, then + 32 to it, and convert the final numeric value into a char
    end;
  end;
  lowcase := s;
end;

Dani AI

Generated

’s routine works for basic ASCII but has a few subtle bugs and edge cases worth calling out.

First, the range test ['A'..'z'] is wrong: that includes non-letter characters between Z and a (for example [ \ ] ^ _ `), so those will be shifted too. Second, doing s := upcase(s) then adding 32 is redundant and confusing. Third, the ord/chr+32 trick assumes plain ASCII; it breaks for accented letters, other code pages, and Unicode strings.

A safer ASCII-only variant (keeps intent but fixes the range and avoids a magic 32) looks like this:

function LowcaseAscii(const S: string): string;
var
  i: Integer;
  Offset: Integer;
begin
  Result := S;
  Offset := Ord('a') - Ord('A'); // portable offset instead of literal 32
  for i := 1 to Length(Result) do
    if Result[i] in ['A'..'Z'] then
      Result[i] := Chr(Ord(Result[i]) + Offset);
end;

For real-world code prefer the runtime library’s case routines instead of rolling your own. The RTL provides locale- and encoding-aware functions (e.g. the LowerCase/AnsiLowerCase-family) that handle diacritics and Unicode correctly and are usually faster. pointed this out earlier.

Quick troubleshooting notes: if you see strange symbols after conversion, check the character-range test and whether your string is Unicode or an Ansi/codepage string. For case-insensitive comparisons consider using the RTL compare helpers (CompareText/SameText) rather than converting strings manually.

TrustyTony 888 ex-Moderator Team Colleague Featured Poster
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.