Page 1 of 1
Finding matches in a string...
Posted: Fri Feb 15, 2008 6:22 am
by bjb007
I have a string
2,14,1,5,19....etc.
I want to count the number of occurences of 1
but looping through the string also counts 14 and 19
etc. as being '1'. Same for 2,3, etc. as there will
be 21,22....31,32... in the string.
How can I prevent 14 etc. being counted as 1, 24 as 2 etc.?
Possible fixes all seem convoluted.
Posted: Fri Feb 15, 2008 6:45 am
by malte
A script would be helpful here.
You can take a look at matchtext an wholematches in the dictionary. However, there may be different solutions, that would require to see your scripts.
All the best,
Malte
Finding matches in a string...
Posted: Fri Feb 15, 2008 7:45 am
by bjb007
OK malte...
----------------------------------------------------------
put url ("file:" & "numbers.txt") into myData
put myData & "1," into myData
put item -36 to -1 of myData into theString
put myData into url ("file:" & "numbers.txt")
put 0 into theCount
repeat with i = 1 to 36
if item i of theString = item 1 of theString then
add 1 to theCount
end if
end repeat
-----------------------------------------------------------
item 1 is 1
Always true for the first comparison since 1 has just
been added to myData but do it to get theCount.
BTW I do format with indents but submit removes it.
P.S. Why do I keep typing theCount = 0?
Because it's the standard way of putting a value into
a variable - except in Rev!
Posted: Fri Feb 15, 2008 6:04 pm
by BvG
The code, as you posted it, seems to do what you want, and I can use it to count items. Maybe that is not actually what you want? Of course you have to make sure that the file exists, and that it's contents always has a comma at the end.
As an alternative, I suggest you try this code, it's easier to use and faster:
Code: Select all
put url ("file:" & "numbers.txt") into myData
put "1," after myData
put item -36 to -1 of myData into theString
put myData into url ("file:" & "numbers.txt")
put item 1 of theString into theCompare
repeat for each item theItem in theString
if theCompare = theItem then
add 1 to theCount
end if
end repeat
To keep intendation intact when posting to the forum, you need to use the code button in the editor, or write the code tags, as specified in the
BBCode help page.
Finding matches in a string...
Posted: Fri Feb 15, 2008 7:11 pm
by bjb007
Thanks BvG - that did the trick.
I got it to work by hard-coding the number to compare
to but wanted generic code so that I could use the
different numbers "on-the-fly".
I had to mod this line...
put item 1 of theString into theCompare
to
put item -1 of theString into theCompare
as I wanted the last number in the string.
BTW I was pleased to find the "step" option in the
"repeat" docs i.e.
repeat for i = 1 to 36 step 4
would only check 1,5,9...etc.