Mega Code Archive

 
Categories / Delphi / String
 

Reverse a string

Title: reverse a string? function ReverseString1(const s: string): string; var i, len: Integer; begin len := Length(s); SetLength(Result, len); for i := len downto 1 do begin Result[len - i + 1] := s[i]; end; end; function ReverseString2(const Str: string): string; // by Ido Kanner var ch: Char; i, Size: Integer; begin Result := Str; Size := Length(Result); if (Size = 2) then // 2 or more chars begin // For 1 to middle of the string for i := 1 to (Size div 2) do begin // Lets get the charecter of the current place in the string ch := Result[i]; // Place the Current pos of the char // with the char of it's mirror place... Result[i] := Result[Size - (i - 1)]; // In the mirror place we will put char of the // Original place... And we switched places !!! Result[Size - (i - 1)] := ch; end end; end; function ReverseString3(S: string): string; // by Rudy Velthuis var P, Q: PChar; C: Char; begin Result := S; if Length(Result) = 0 then Exit; P := PChar(Result); Q := P + Length(Result) - 1; while P do begin C := P^; P^ := Q^; Q^ := C; Inc(P); Dec(Q); end; end; procedure ReverseString4(var S: string); // by Rudy Velthuis var P, Q: PChar; C: Char; begin if Length(S) = 0 then Exit; P := PChar(S); Q := P + Length(S) - 1; while P do begin C := P^; P^ := Q^; Q^ := C; Inc(P); Dec(Q); end; end;