Articles   Members Online:
-Article/Tip Search
-News Group Search over 21 Million news group articles.
-Delphi/Pascal
-CBuilder/C++
-C#Builder/C#
-JBuilder/Java
-Kylix
Member Area
-Home
-Account Center
-Top 10 NEW!!
-Submit Article/Tip
-Forums Upgraded!!
-My Articles
-Edit Information
-Login/Logout
-Become a Member
-Why sign up!
-Newsletter
-Chat Online!
-Indexes NEW!!
Employment
-Build your resume
-Find a job
-Post a job
-Resume Search
Contacts
-Contacts
-Feedbacks
-Link to us
-Privacy/Disclaimer
Embarcadero
Visit Embarcadero
Embarcadero Community
JEDI
Links
How to find values in a string Turn on/off line numbers in source code. Switch to Orginial background IDE or DSP color Comment or reply to this aritlce/tip for discussion. Bookmark this article to my favorite article(s). Print this article
19-Oct-02
Category
Object Pascal-Strings
Language
Delphi 2.x
Views
47
User Rating
No Votes
# Votes
0
Replies
0
Publisher:
DSP, Administrator
Reference URL:
DKB
			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;

			
Vote: How useful do you find this Article/Tip?
Bad Excellent
1 2 3 4 5 6 7 8 9 10

 

Advertisement
Share this page
Advertisement
Download from Google

Copyright © Mendozi Enterprises LLC