Java Reference
In-Depth Information
Constructs a new
String
whose contents are the same as the
chars
array, from index
start
up to a maximum of
count
char-
acters.
public
String(char[] chars)
Equivalent to
String(chars,0, chars.length)
.
Both of these constructors make copies of the array, so you can change
the array contents after you have created a
String
from it without af-
fecting the contents of the
String
.
For example, the following simple algorithm squeezes out all occur-
rences of a character from a string:
public static String squeezeOut(String from, char toss) {
char[] chars = from.toCharArray();
int len = chars.length;
int put = 0;
for (int i = 0; i < len; i++)
if (chars[i] != toss)
chars[put++] = chars[i];
return new String(chars, 0, put);
}
The method
squeezeOut
first converts its input string
from
into a character
array using the method
toCharArray
. It then sets up
put
, which will be the
next position into which to put a character. After that it loops, copying
into the array any character that isn't a
toss
character. When the meth-
od is finished looping over the array, it returns a new
String
object that
contains the squeezed string.
You can use the two static
String.copyValueOf
methods instead of the
constructors if you prefer. For instance,
squeezeOut
could have been
ended with
return String.copyValueOf(chars, 0, put);