2005. október 13., csütörtök
How to find values in a string
Problem/Question/Abstract:
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:
type
TIntArray = array of integer
procedure StringToIntArray(const S: string; var List: TIntArray);
{ Converts "S" to an array of integer -> "List" }
const
ValidChars: set of char = ['0'..'9', '-'];
var
Ix, Ix2, Len, C: Integer;
SubStr: string;
Value, Code: Integer;
begin
Len := Length(S);
SetLength(List, Len);
if Len = 0 then
Exit;
C := 0;
Ix := 1;
while Ix <= Len do
begin
while (Ix <= Len) and (not (S[Ix] in ValidChars)) do
Inc(Ix);
Ix2 := Ix;
while (Ix <= Len) and (S[Ix] in ValidChars) do
Inc(Ix);
SubStr := Copy(S, Ix2, Ix - Ix2);
Val(SubStr, Value, Code);
if Code = 0 then
begin
List[C] := Value;
Inc(C);
end;
end;
SetLength(List, C);
end;
function FindValue(Value: Integer; List: TIntArray): Integer;
{ Returns index of requested value, or -1 if not found. }
var
Ix: Integer;
begin
Result := -1;
Ix := 0;
while Ix < Length(List) do
begin
if List[Ix] = Value then
begin
Result := Ix;
Exit;
end;
Inc(Ix);
end;
end;
Example:
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;
Feliratkozás:
Megjegyzések küldése (Atom)
Nincsenek megjegyzések:
Megjegyzés küldése