Author: Jonas Bilinkevicius
I have a string which contains values separated by "," and not necessarily in
numeric order (1, 50, 100, 2, 5, 10, ...). What is the best and fastest way to
search through this string to find a value, for example 100?
Answer:
1 type
2 TIntArray = array of integer
3
4 procedure StringToIntArray(const S: string; var List: TIntArray);
5 { Converts "S" to an array of integer -> "List" }
6 const
7 ValidChars: set of char = ['0'..'9', '-'];
8 var
9 Ix, Ix2, Len, C: Integer;
10 SubStr: string;
11 Value, Code: Integer;
12 begin
13 Len := Length(S);
14 SetLength(List, Len);
15 if Len = 0 then
16 Exit;
17 C := 0;
18 Ix := 1;
19 while Ix <= Len do
20 begin
21 while (Ix <= Len) and (not (S[Ix] in ValidChars)) do
22 Inc(Ix);
23 Ix2 := Ix;
24 while (Ix <= Len) and (S[Ix] in ValidChars) do
25 Inc(Ix);
26 SubStr := Copy(S, Ix2, Ix - Ix2);
27 Val(SubStr, Value, Code);
28 if Code = 0 then
29 begin
30 List[C] := Value;
31 Inc(C);
32 end;
33 end;
34 SetLength(List, C);
35 end;
36
37 function FindValue(Value: Integer; List: TIntArray): Integer;
38 { Returns index of requested value, or -1 if not found. }
39 var
40 Ix: Integer;
41 begin
42 Result := -1;
43 Ix := 0;
44 while Ix < Length(List) do
45 begin
46 if List[Ix] = Value then
47 begin
48 Result := Ix;
49 Exit;
50 end;
51 Inc(Ix);
52 end;
53 end;
54
55 //Example:
56
57 StringToIntArray('(1, 50, 100, 2, 5, 10,.....)', MyIntArray)
sets the contents of MyIntArray to [1,50,100,2,5,10].
then FindValue(100, MyIntArray) returns 2, as MyIntArray[2] = 100;
|