Perfect Developer tutorial | This page last modified 15 December 2004 (JAC) |
1. When the character variable lastCharacter
has the value `H`
,
which of the following expressions will be true?
lastCharacter.isLetter
lastCharacter.isDigit
lastCharacter.isPrintable
char{+lastCharacter} = `H`
>lastCharacter = `I`
(>lastCharacter).isLetter
Expressions 1, 3 and 4 will be true, and expression 2 false, for any implementation.
Expressions 5 and 6 will also be true provided the underlying
implementation uses a reasonable character set (e.g. ASCII or Unicode).
2. You have two character variables firstChar
and secondChar
which are known to both represent digits
(i.e. firstChar.isDigit & secondChar.isDigit
is true).
Which of the following expressions should you use to convert these to an integer, such that firstChar is the tens-digit
and secondChar is the units-digit?
10 * firstCharacter + secondCharacter
10 * (firstCharacter - `0`) + (secondCharacter - `0`)
10 * (+firstCharacter) + (+secondCharacter)
10 * (+firstCharacter - +`0`) + (+secondCharacter -
+`0`)
10 * firstCharacter.digit + secondCharacter.digit
Expression 1 is not well-formed because there is no automatic type conversion from
char to int.
Expression 2 is not well-formed because there is no subtraction operator defined between operands of type
char.
Expression 3 gives the wrong answer, because for common character sets, +`0` is not equal to 0.
Expression 4 will work for most character sets (including ASCII and Unicode).
Expression 5 is best as it is guaranteed to work for all character sets.