Java Reference
In-Depth Information
Running this code, we get
a is before z
Code ASCII for a:97
Code ASCII for z:122
One can convert a lower-case string to an upper-case string by performing the
following
arithmetic
operations on characters (with
char
⇔
int
casting):
Program 5.9
Lower-case to upper-case string conversion
static
String LowerToUpper(String s)
{
String result=
""
;
char
c;
for
(
int
i=0;i
<
s . length () ; i++)
c=(
char
)(s.charAt(i)
−
32) ;
//32=2^5
result+=c;
//concatenation, append c to result
return
result ;
}
...
String s=LowerToUpper(
"convert a simple sentence"
);
To compare string
s
1
with string
s
2
, we first need to define a
total order
between
these strings so that we can report whatever the input strings whether
-
s
1
<s
2
,
-
s
1
=
s
2
or
-
s
1
>s
2
.
This total order is called the
lexicographic order
and is defined for strings as
follows:
-
If one string is a
substring
of another one, then report the length difference:
Positive or negative number. Zero if and only if the strings are exactly the
same.
-
Otherwise, there necessarily exists an index where the two string characters
differ. Report then the difference in ASCII code of these two different
characters.
To lexicographically compare two strings in Java, use the method
compareTo(str)
method as follows:
String u="Polyhedron", v="Polyhedral";
System.out.println(u.compareTo(v));
// => 14= 'o'-'a'=111-97;
Search WWH ::
Custom Search