10. Strings and String Processing

10.7. Example: Processing Names and Passwords

Many computer systems store user names and passwords as delimited strings, such as

,,

 

 

 

 

 

 

Algorithm design


J

Obviously, if the system is going to process passwords, it needs some way to take apart these name-password pairs.

Let’s write methods to help perform this task. The first method will be passed a name-password pair and will return the name. The second method will be passed a name-password pair and will return the pass- word. In both cases, the method takes a single String parameter and returns a String result:

 

,,

 

J

To solve this problem we can make use of two String methods. We use the indexOf() method to find the location of the delimiter—which is the colon, “:”—in the name-password pair and then we use substring() to take the substring occurring before or after the delimiter. It may be easier to see this if we take a particular example:

,,

 

 

 

J

In the first case, the delimiter occurs at index position 5 in the string. Therefore, to take the name substring, we would use substring(0,5).

 

To take the password substring, we would use substring(6). Of course, in the general case, we would use variables to indicate the position of the delimiter, as in the following methods:

,,

 

 

 

 

 

 

 

 

J

Note in both of these cases we have used local variables, posColon and result, to store the intermediate results of the computation—that is, the index of the “:” and the name or password substring.

An alternative way to code these operations would be to use nested method calls to reduce the code to a single line:

,,

 

J

In this line, the result of str.indexOf(’:’) is passed immediately as the second argument to str.substring(). This version dispenses with the need for additional variables. And the result in this case is not unrea- sonably complicated. But whenever you are faced with a trade-off of this sort—nesting versus additional variables—you should opt for the style that will be easier to read and understand.