Java Reference
In-Depth Information
The
replaceAll
,
replaceFirst
, and
split
methods can be used with a regular
expression. For example, the following statement returns a new string that replaces
$
,
+
, or
#
in
a+b$#c
with the string
NNN
.
String s =
"a+b$#c"
.replaceAll(
"[$+#]"
,
"NNN"
);
System.out.println(s);
replaceAll(regex)
Here the regular expression
[$+#]
specifies a pattern that matches
$
,
+
, or
#
. So, the output
is
aNNNbNNNNNNc
.
The following statement splits the string into an array of strings delimited by punctuation marks.
String[] tokens =
"Java,C?C#,C++"
.split(
"[.,:;?]"
);
split(regex)
for
(
int
i =
0
; i < tokens.length; i++)
System.out.println(tokens[i]);
In this example, the regular expression
[.,:;?]
specifies a pattern that matches
.
,
,
,
:
,
;
, or
?
. Each of these characters is a delimiter for splitting the string. Thus, the string is split into
Java
,
C
,
C#
, and
C++
, which are stored in array
tokens
.
Regular expression patterns are complex for beginning students to understand. For this
reason, simple patterns are introduced in this section. Please refer to Appendix H, Regular
Expressions, to learn more about these patterns.
further studies
10.10.5 Conversion between Strings and Arrays
Strings are not arrays, but a string can be converted into an array, and vice versa. To convert a
string into an array of characters, use the
toCharArray
method. For example, the following
statement converts the string
Java
to an array.
toCharArray
char
[] chars =
"Java"
.toCharArray();
Thus,
chars[0]
is
J
,
chars[1]
is
a
,
chars[2]
is
v
, and
chars[3]
is
a
.
You can also use the
getChars(int srcBegin, int srcEnd, char[] dst,
int dstBegin)
method to copy a substring of the string from index
srcBegin
to index
srcEnd-1
into a character array
dst
starting from index
dstBegin
. For example, the fol-
lowing code copies a substring
"3720"
in
"CS3720"
from index
2
to index
6-1
into the
character array
dst
starting from index
4
.
char
[] dst = {
'J'
,
'A'
,
'V'
,
'A'
,
'1'
,
'3'
,
'0'
,
'1'
};
"CS3720"
.getChars(
2
,
6
, dst,
4
);
getChars
Thus,
dst
becomes
{'J', 'A', 'V', 'A', '3', '7', '2', '0'}
.
To convert an array of characters into a string, use the
String(char[])
constructor or
the
valueOf(char[])
method. For example, the following statement constructs a string
from an array using the
String
constructor.
String str =
new
String(
new char
[]{
'J'
,
'a'
,
'v'
,
'a'
});
The next statement constructs a string from an array using the
valueOf
method.
valueOf
String str = String.valueOf(
new char
[]{
'J'
,
'a'
,
'v'
,
'a'
});
10.10.6 Converting Characters and Numeric Values to Strings
Recall that you can use
Double.parseDouble(str)
or
Integer.parseInt(str)
to
convert a string to a
double
value or an
int
value and you can convert a character or a
number into a string by using the string concatenating operator. Another way of converting a
Search WWH ::
Custom Search