Wednesday, July 7, 2010

How to capitalize a string

Ever needed to capitalize a string and keep the rest lower case? here's my implementation...
I use this function when the OnExit event is triggered in a edit control – usually in user name/password fields etc.
function CapitalizeString(const s: string; const CapitalizeFirst: Boolean = True): string;
const
  ALLOWEDCHARS = ['a'..'z', '_'];
var
  Index: Integer;
  bCapitalizeNext: Boolean;
begin
  bCapitalizeNext := CapitalizeFirst;
  Result := LowerCase(s);
  if Result <> EmptyStr then
    for Index := 1 to Length(Result) do
      if bCapitalizeNext then begin
        Result[Index] := UpCase(Result[Index]);
        bCapitalizeNext := False;
      end else
      if NOT CharInSet(Result[Index], ALLOWEDCHARS) then
        bCapitalizeNext := True;
end;

No comments:

Post a Comment

Blogroll(General programming and Delphi feeds)