1. String compare
Hi All
I'm trying to compare two strings.
-- example
object st
st="ABC"
if st="ABC" then puts(1,"OK") end if
The above ends in an error message. In QBASIC a similar program works just
fine. Can someone please tell me where I'm going wrong. Thanks for putting
me right.
Regards,
Roy
2. Re: String compare
Roy wrote:
>I'm trying to compare two strings.
You can only use '=' on basic types. For reasons that continue to irritate
me, Robert has chose to follow the C model and require a function call for
more complex comparisons:
if compare( st, "abc" ) = 0 then
will work. Essentially, you can think of compare() as subtracting the two
value. It returns -1, 0 or 1 depending on if the values are less than,
equal, or greater than each other.
A common error (not just newbie; I make it all the time) is to write:
if compare( st, "abc" ) then
which is the opposite of what you want. It might be helpful to write your
own function, along the lines of:
function eq( object o1, object o2 )
return compare( o1, o2 ) = 0
end function
so you can write:
if eq( st, '123" ) then
instead.
Hope this helps!
-- David Cuny
3. Re: String compare
Roy Shepherd wrote:
> I'm trying to compare two strings.
> -- example
> object st
> st="ABC"
> if st="ABC" then puts(1,"OK") end if
another option, perhaps until you become more fluent in Euph's
syntax, besides the one offered by David
(using compare(st,"abc") = 0 or the function solution below:
-- function IsSame(object a,object b)
return compare(a,b)=0
end function
)
another option might be to remember that (in essence) strings
are arrays (sequences) of characters.
you can walk the array, and you can use the = sign for
character comparisons.
--constant Mary="Mary had a little piggy, whose fleece was skin"
--to find out if a string has a 'p' in it, you can do
-- for index = 1 to length(Mary) do
if Mary[index] = 'p' then Found=TRUE end if
end for
now, this is def'nly not the best way to test for string
equality, but for some cases, it works well, and it may
help you to think with sequences.
a hard coded 'compare' function would then look (actually, not
at all) like the following (in theory, as an algorithmic ex.):
constant Mary1="mary had a little pig"
constant Mary2="mary had a little gip"
IsSame = FALSE
--you need the following test, or the variable index will go out of
bounds
if length(Mary1) = length(Mary2) then
IsSame = TRUE
end if
index = 1
while IsSame and (index <= length(Mary1)) do
if Mary1[index] != Mary2[index] then
IsSame=FALSE
end if
index = index + 1
end while
if IsSame then puts(1,"They match\n")
else puts(1,"They do not match\n")
end if
hopefully, this will help you see the slight differences in character
versus string equality??? hope so :)
enjoy--Hawke'