10.6 Comparing Strings


10.6 Comparing Strings

In KJP, a string s1 can be compared with another string s2 using the equals operator. This operator compares two strings and evaluates to a truth-value, so it can be used with an if statement. The general syntax for this operator follows—variable str_var1 is compared to str_var2.

       if  str_var1  equals  str_var2  

For example, the following statement tests if string s1 is equal to string s2:

       variables          string s1          string s2          . . .       begin          . . .          if s1 equals s2          then             . . . 

Another operator for string comparison is the compareto operator, which compares two strings and evaluates to an integer value. If this integer value is zero, the two strings are equal. If the integer value is greater than zero, the first string is higher alphabetically with respect to the second string. If the integer value is less than zero, the first string is lower alphabetically with respect to the second string. The compareto operator is used in an assignment statement. The general structure of an assignment statement with this operator follows.

        set  int_var  =  str_var1  compareto  str_var2  

For example, the following KJP code compares string variables s1 and s2 in an assignment statement with integer variable test. This integer variable is then tested in an if statement for various possible sets of instructions.

       variables          string s1          string s2          integer test  // result of string comparison          . . .       begin          . . .          set test = s1 compareto s2          if test == 0          then             . . .          if test > 0          then             . . .          else             . . . 

In the example, variable test holds the integer values with the result of the string comparison of s1 and s2. Variable test is subsequently evaluated in an if statement for further processing.




Object-Oriented Programming(c) From Problem Solving to Java
Object-Oriented Programming (From Problem Solving to JAVA) (Charles River Media Programming)
ISBN: 1584502878
EAN: 2147483647
Year: 2005
Pages: 184

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net