Reputation: 373
Long time reader, first time poster, I'm turning to you because I so many times found answers to my questions here, that I'm sure this one will be just a formality for this great community :)
My question might seem odd, even newbish, but I'm building an application for parsing text lines with urls.
A the beginning of the code, the first step is to determine how many urls there are in the text block. I do it by using the "copy" function from the beginning till the end of the text block, looking for the tag "a href=" tag.
This works fine.
Here is the code :
Tag := '<a href="';
Longueur := Length(ArtistNBSource);
Result := 0;
For i := 1 to Longueur do
begin
Copied := Copy(ArtistNBSource,i,Length(Tag));
if Copied = Tag then inc(Result)
end;
ARTIST_COUNT := Result;
Now, depending on the number of urls found, I'm going to loop through the text block.
What I would like to avoid is things like this...
if Result : 1 do
begin
some instruction
end
else if Result = 2
begin
other instruction
end
else if Result = 3....
...because with a maximum of 5 url possible in the text block, that would give me a veryyyyy long code.
What I imagined was this :
First of all, I declare variables up to the maximum known possible.
var
AUPOS1, AUPOS2, AUPOS3, AUPOS4, AUPOS5, ANPOS1, ANPOS2, ANPOS3, ANPOS4, ANPOS5, ia : Integer;
As the parsing patern is fixed, I imagined this :
For ia := 1 to ARTIST_COUNT do
begin
(AUPOS+IntToStr(ia)):= Pos('">', ArtistNBSource);
(AURL+IntToStr(ia)) := Copy(ArtistNBSource,11,(AUPOS+IntToStr(ia))-11);
Delete(ArtistNBSource,1,(AUPOS+IntToStr(ia))+1);
(ANPOS+IntTostr(ia)) := Pos('</a>', ArtistNBSource);
(ANAME+IntToStr(ia)) := Copy(ArtistNBSource,1,(ANPOS+IntToStr(ia))-1);
Delete(ArtistNBSource, 1,(ANPOS+IntToStr(ia))+4);
end;
The ia variable matching the number of loops AND the variables names for each loop, I thought I could auto increment the variables names and assign their values to the previously declared variables.
But of course this does not work :)
My question :
Do any of you see a solution out of this ?
Am I condemned to writing the 'if then' long sequence, or can I dynamically adjust variable names through the loop ?
Thank you all in advance for any comment that might give me a clue of what direction to follow.
Cheers
Mathmathou.
Upvotes: 1
Views: 2208
Reputation: 535
I would recommend having just one variable - a dictionary/hash table and then have the 'dynamic variable names' be keys in that dictionary and the values be what you would store in those 'dynamically named' variables.
Here is a tutorial about dictionaries:
http://beensoft.blogspot.se/2008/09/simple-generic-dictionary-tdictionary.html
Upvotes: 1