Author: William Gerbert
How to reverse a string
Answer:
Here are three examples how to reverse a string:
#1, While easy to understand suffers from a lot of memory reallocation. Each time
the next letter is added to s2, it's added to the beginning of the string causing a
reallocation of the entire string.
1 function ReverseString(s: string): string;
2 var
3 i: integer;
4 s2: string;
5 begin
6 s2 := '';
7 for i := 1 to Length(s) do
8 s2 := s[i] + s2;
9 Result := s2;
10 end;
#2, Taking advantage of the fact that we can work at both ends of the string at
once AND the fact that IF there is a middle character, ie. an odd number of
characters in the string, it doesn't change position at all and we can eliminate
all the memory allocations, work completely within the source string swapping from
end to end working toward the middle and only having to make 1/2 of a loop through
the string.
11 procedure ReverseStr(var Src: string);
12 var
13 i, j: integer;
14 C1: char;
15 begin
16 j := Length(Src);
17 for i := 1 to (Length(Src) div 2) do
18 begin
19 C1 := Src[i];
20 Src[i] := Src[j];
21 Src[j] := C1;
22 Dec(j);
23 end;
24 end;
#3, One disadvantage of #2 can be seen when trying to fill one control with the
contents of another. For example, two TEdits. Since TEdit.Text can't be sent as a
var parameter you'll need to first make use of a temporary string and then set the
second TEdit:
25 var
26 tStr: string;
27 begin
28 tStr := Edit1.Text;
29 ReverseStr(tStr);
30 Edit2.Text := tStr;
However, using #3 this code turns into,
Edit2.Text := ReverseStr(Edit1.Text);
In addition, we lost 1 local var and the loop body was reduced since we could use
Result directly swapping as we go!
31 function ReverseStr(const Src: string): string;
32 var
33 i, j: integer;
34 begin
35 j := Length(Src);
36 SetLength(Result, j);
37 for i := 1 to (Length(Src) div 2) do
38 begin
39 Result[i] := Src[j];
40 Result[j] := Src[i];
41 Dec(j);
42 end;
43 end;
|