Title: TitleCase()
Question: Looking for a blazing fast function to capitalize the first letter of every word in a string?
Answer:
Benchmarks on a Pentium III 933 MHz PC with a five word, 55 character string, after 1,000,000 iterations, yielded an average execution time of 0.74 microseconds (i.e., less than one thousandth of a millisecond).
function TitleCase(const S: string): string;
var
AChar, APrevChar: Char;
ALength: Integer;
ASource, ADest: PChar;
begin
// Set defaults
ALength := Length(S);
SetLength(Result, ALength);
ASource := Pointer(S);
ADest := Pointer(Result);
// Nothing to parse?
if not Assigned(ASource) then
Exit;
// Get first char
AChar:= ASource^;
// Convert to Upper Case
if (AChar = 'a') and (AChar then
Dec(AChar, 32);
// Add char to Result
ADest^ := AChar;
// Move to next char in string
Inc(ASource);
Inc(ADest);
// Count down
Dec(ALength);
// Loop through remaining string
while ALength 0 do
begin
// Store previous char
APrevChar := AChar;
// Get next char
AChar:= ASource^;
// Was previous char a space?
if APrevChar = ' ' then
begin
// Convert to Upper Case
if (AChar = 'a') and (AChar then
Dec(AChar, 32)
end
// Convert to Lower Case
else if (AChar = 'A') and (AChar then
Inc(AChar, 32);
// Add char to Result
ADest^ := AChar;
// Move to next char in string
Inc(ASource);
Inc(ADest);
// Count down
Dec(ALength);
end;
end;