Thursday, 16 August 2007

Operators and Assignments (Part 9)

Strings - cont

Sequencing Strings
When you have a collection of names and you want to place them in order, testing for equality is not going to work. What you need is a method compareTo() which is defined in the class String.

The method is called as follows:
string1.compareTo(string2);

It returns an integer which is negative if the string object is less than the argument passed, zero if they are both equal and positive integer if the string object is greater than the argument passed.

Strings are compared by comparing individual corresponding characters, starting with the first character in each string, until two corresponding characters are found to be different or the last character in the shorter string is reached. Individual characters are compared by comparing their numeric values, so two characters are equal if the numeric value of the UniCodeText character are equal. For example, if string1 has the value “anil” and string2 has value “anirudh”, then the expression,
string1.compareTo(string2);
will return a negative value as a result of comparing the fourth characters in the strings.

Exercise 3 – 3 Comparing Strings

Create at least 2 variables of type String (call them name1, name2) and then store the names Rover and Citroen in that order. Now rearrange them so that they will be stored in an alphabetical order (in other words, name1 will contain Citroen). Finally display them on the screen in the new order.

Exercise 3 – 4 Comparing 2 strings using parameters

Now adapt the last exercise to take in parameters from the command line (the String args[] part of main) so that you can compare any two strings when you run the application. This exercise is a little difficult at this point as it uses arrays. Arrays are covered in a later section. For now, use the online documentation to help you solve the exercise

No comments:

Post a Comment