Stringpublic final class String extends Object The String class represents character strings. All
string literals in Java programs, such as "abc" , are
implemented as instances of this class.
Strings are constant; their values cannot be changed after they
are created. String buffers support mutable strings.
Because String objects are immutable they can be shared. For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
Here are some more examples of how strings can be used:
System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2,3);
String d = cde.substring(1, 2);
The class String includes methods for examining
individual characters of the sequence, for comparing strings, for
searching strings, for extracting substrings, and for creating a
copy of a string with all characters translated to uppercase or to
lowercase.
The Java language provides special support for the string
concatenation operator ( + ), and for conversion of
other objects to strings. String concatenation is implemented
through the StringBuffer class and its
append method.
String conversions are implemented through the method
toString , defined by Object and
inherited by all classes in Java. For additional information on
string concatenation and conversion, see Gosling, Joy, and Steele,
The Java Language Specification. |
Fields Summary |
---|
private char[] | valueThe value is used for character storage. | private int | offsetThe offset is the first index of the storage that is used. | private int | countThe count is the number of characters in the String. |
Constructors Summary |
---|
public String()Initializes a newly created String object so that it
represents an empty character sequence.
value = new char[0];
| String(int offset, int count, char[] value)
this.value = value;
this.offset = offset;
this.count = count;
| public String(String value)Initializes a newly created String object so that it
represents the same sequence of characters as the argument; in other
words, the newly created string is a copy of the argument string.
count = value.length();
this.value = new char[count];
value.getChars(0, count, this.value, 0);
| public String(char[] value)Allocates a new String so that it represents the
sequence of characters currently contained in the character array
argument. The contents of the character array are copied; subsequent
modification of the character array does not affect the newly created
string.
this.count = value.length;
this.value = new char[count];
System.arraycopy(value, 0, this.value, 0, count);
| public String(char[] value, int offset, int count)Allocates a new String that contains characters from
a subarray of the character array argument. The offset
argument is the index of the first character of the subarray and
the count argument specifies the length of the
subarray. The contents of the subarray are copied; subsequent
modification of the character array does not affect the newly
created string.
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.value = new char[count];
this.count = count;
System.arraycopy(value, offset, this.value, 0, count);
| public String(byte[] bytes, int off, int len, String enc)Construct a new String by converting the specified
subarray of bytes using the specified character encoding. The length of
the new String is a function of the encoding, and hence may
not be equal to the length of the subarray.
this(Helper.byteToCharArray(bytes, off, len, enc));
| public String(byte[] bytes, String enc)Construct a new String by converting the specified array
of bytes using the specified character encoding. The length of the new
String is a function of the encoding, and hence may not be
equal to the length of the byte array.
this(bytes, 0, bytes.length, enc);
| public String(byte[] bytes, int off, int len)Construct a new String by converting the specified
subarray of bytes using the platform's default character encoding. The
length of the new String is a function of the encoding, and
hence may not be equal to the length of the subarray.
this(Helper.byteToCharArray(bytes, off, len));
| public String(byte[] bytes)Construct a new String by converting the specified array
of bytes using the platform's default character encoding. The length of
the new String is a function of the encoding, and hence may
not be equal to the length of the byte array.
this(bytes, 0, bytes.length);
| public String(StringBuffer buffer)Allocates a new string that contains the sequence of characters
currently contained in the string buffer argument. The contents of
the string buffer are copied; subsequent modification of the string
buffer does not affect the newly created string.
synchronized(buffer) {
buffer.setShared();
this.value = buffer.getValue();
this.offset = 0;
this.count = buffer.length();
}
|
Methods Summary |
---|
public native char | charAt(int index)Returns the character at the specified index. An index ranges
from 0 to length() - 1 . The first character
of the sequence is at index 0 , the next at index
1 , and so on, as for array indexing.
| public int | compareTo(java.lang.String anotherString)Compares two strings lexicographically.
The comparison is based on the Unicode value of each character in
the strings. The character sequence represented by this
String object is compared lexicographically to the
character sequence represented by the argument string. The result is
a negative integer if this String object
lexicographically precedes the argument string. The result is a
positive integer if this String object lexicographically
follows the argument string. The result is zero if the strings
are equal; compareTo returns 0 exactly when
the {@link #equals(Object)} method would return true .
This is the definition of lexicographic ordering. If two strings are
different, then either they have different characters at some index
that is a valid index for both strings, or their lengths are different,
or both. If they have different characters at one or more index
positions, let k be the smallest such index; then the string
whose character at position k has the smaller value, as
determined by using the < operator, lexicographically precedes the
other string. In this case, compareTo returns the
difference of the two character values at position k in
the two string -- that is, the value:
this.charAt(k)-anotherString.charAt(k)
If there is no index position at which they differ, then the shorter
string lexicographically precedes the longer string. In this case,
compareTo returns the difference of the lengths of the
strings -- that is, the value:
this.length()-anotherString.length()
int len1 = count;
int len2 = anotherString.count;
int n = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
if (i == j) {
int k = i;
int lim = n + i;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
} else {
while (n-- != 0) {
char c1 = v1[i++];
char c2 = v2[j++];
if (c1 != c2) {
return c1 - c2;
}
}
}
return len1 - len2;
| public java.lang.String | concat(java.lang.String str)Concatenates the specified string to the end of this string.
If the length of the argument string is 0 , then this
String object is returned. Otherwise, a new
String object is created, representing a character
sequence that is the concatenation of the character sequence
represented by this String object and the character
sequence represented by the argument string.
Examples:
"cares".concat("s") returns "caress"
"to".concat("get").concat("her") returns "together"
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
char buf[] = new char[count + otherLen];
getChars(0, count, buf, 0);
str.getChars(0, otherLen, buf, count);
return new String(0, count + otherLen, buf);
| public boolean | endsWith(java.lang.String suffix)Tests if this string ends with the specified suffix.
return startsWith(suffix, count - suffix.count);
| public native boolean | equals(java.lang.Object anObject)Compares this string to the specified object.
The result is true if and only if the argument is not
null and is a String object that represents
the same sequence of characters as this object.
| public boolean | equalsIgnoreCase(java.lang.String anotherString)Compares this String to another String ,
ignoring case considerations. Two strings are considered equal
ignoring case if they are of the same length, and corresponding
characters in the two strings are equal ignoring case.
Two characters c1 and c2 are considered
the same, ignoring case if at least one of the following is true:
- The two characters are the same (as compared by the
== operator).
- Applying the method {@link java.lang.Character#toUpperCase(char)}
to each character produces the same result.
- Applying the method {@link java.lang.Character#toLowerCase(char)}
to each character produces the same result.
return (anotherString != null) && (anotherString.count == count) &&
regionMatches(true, 0, anotherString, 0, count);
| public byte[] | getBytes(java.lang.String enc)Convert this String into bytes according to the specified
character encoding, storing the result into a new byte array.
return Helper.charToByteArray(value, offset, count, enc);
| public byte[] | getBytes()Convert this String into bytes according to the platform's
default character encoding, storing the result into a new byte array.
return Helper.charToByteArray(value, offset, count);
| public void | getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)Copies characters from this string into the destination character
array.
The first character to be copied is at index srcBegin ;
the last character to be copied is at index srcEnd-1
(thus the total number of characters to be copied is
srcEnd-srcBegin ). The characters are copied into the
subarray of dst starting at index dstBegin
and ending at index:
dstbegin + (srcEnd-srcBegin) - 1
if (srcBegin < 0) {
throw new StringIndexOutOfBoundsException(srcBegin);
}
if (srcEnd > count) {
throw new StringIndexOutOfBoundsException(srcEnd);
}
if (srcBegin > srcEnd) {
throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
}
System.arraycopy(value, offset + srcBegin, dst, dstBegin,
srcEnd - srcBegin);
| public int | hashCode()Returns a hashcode for this string. The hashcode for a
String object is computed as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
using int arithmetic, where s[i] is the
ith character of the string, n is the length of
the string, and ^ indicates exponentiation.
(The hash value of the empty string is zero.)
int h = 0;
int off = offset;
char val[] = value;
int len = count;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
return h;
| public native int | indexOf(int ch)Returns the index within this string of the first occurrence of the
specified character. If a character with value ch occurs
in the character sequence represented by this String
object, then the index of the first such occurrence is returned --
that is, the smallest value k such that:
this.charAt(k) == ch
is true . If no such character occurs in this string,
then -1 is returned.
| public native int | indexOf(int ch, int fromIndex)Returns the index within this string of the first occurrence of the
specified character, starting the search at the specified index.
If a character with value ch occurs in the character
sequence represented by this String object at an index
no smaller than fromIndex , then the index of the first
such occurrence is returned--that is, the smallest value k
such that:
(this.charAt(k) == ch) && (k >= fromIndex)
is true. If no such character occurs in this string at or after
position fromIndex , then -1 is returned.
There is no restriction on the value of fromIndex . If it
is negative, it has the same effect as if it were zero: this entire
string may be searched. If it is greater than the length of this
string, it has the same effect as if it were equal to the length of
this string: -1 is returned.
| public int | indexOf(java.lang.String str)Returns the index within this string of the first occurrence of the
specified substring. The integer returned is the smallest value
k such that:
this.startsWith(str, k)
is true .
return indexOf(str, 0);
| public int | indexOf(java.lang.String str, int fromIndex)Returns the index within this string of the first occurrence of the
specified substring, starting at the specified index. The integer
returned is the smallest value k such that:
this.startsWith(str, k) && (k >= fromIndex)
is true .
There is no restriction on the value of fromIndex . If
it is negative, it has the same effect as if it were zero: this entire
string may be searched. If it is greater than the length of this
string, it has the same effect as if it were equal to the length of
this string: -1 is returned.
char v1[] = value;
char v2[] = str.value;
int max = offset + (count - str.count);
if (fromIndex >= count) {
if (count == 0 && fromIndex == 0 && str.count == 0) {
/* There is an empty string at index 0 in an empty string. */
return 0;
}
/* Note: fromIndex might be near -1>>>1 */
return -1;
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (str.count == 0) {
return fromIndex;
}
int strOffset = str.offset;
char first = v2[strOffset];
int i = offset + fromIndex;
startSearchForFirstChar:
while (true) {
/* Look for first character. */
while (i <= max && v1[i] != first) {
i++;
}
if (i > max) {
return -1;
}
/* Found first character, now look at the rest of v2 */
int j = i + 1;
int end = j + str.count - 1;
int k = strOffset + 1;
while (j < end) {
if (v1[j++] != v2[k++]) {
i++;
/* Look for str's first char again. */
continue startSearchForFirstChar;
}
}
return i - offset; /* Found whole string. */
}
| public native java.lang.String | intern()Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the
class String .
When the intern method is invoked, if the pool already contains a
string equal to this String object as determined by
the {@link #equals(Object)} method, then the string from the pool is
returned. Otherwise, this String object is added to the
pool and a reference to this String object is returned.
It follows that for any two strings s and t ,
s.intern() == t.intern() is true
if and only if s.equals(t) is true .
All literal strings and string-valued constant expressions are
interned. String literals are defined in Section 3.10.5 of the
Java Language
Specification
| public int | lastIndexOf(int ch)Returns the index within this string of the last occurrence of the
specified character. That is, the index returned is the largest
value k such that:
this.charAt(k) == ch
is true.
The String is searched backwards starting at the last character.
return lastIndexOf(ch, count - 1);
| public int | lastIndexOf(int ch, int fromIndex)Returns the index within this string of the last occurrence of the
specified character, searching backward starting at the specified
index. That is, the index returned is the largest value k
such that:
(this.charAt(k) == ch) && (k <= fromIndex)
is true.
int min = offset;
char v[] = value;
for (int i = offset + ((fromIndex >= count) ? count - 1 : fromIndex) ; i >= min ; i--) {
if (v[i] == ch) {
return i - offset;
}
}
return -1;
| public int | length()Returns the length of this string.
The length is equal to the number of 16-bit
Unicode characters in the string.
return count;
| public boolean | regionMatches(boolean ignoreCase, int toffset, java.lang.String other, int ooffset, int len)Tests if two string regions are equal.
A substring of this String object is compared to a substring
of the argument other. The result is true if these
substrings represent character sequences that are the same, ignoring
case if and only if ignoreCase is true. The substring of
this String object to be compared begins at index
toffset and has length len. The substring of
other to be compared begins at index ooffset and
has length len. The result is false if and only if
at least one of the following is true:
- toffset is negative.
- ooffset is negative.
- toffset+len is greater than the length of this
String object.
- ooffset+len is greater than the length of the other
argument.
- There is some nonnegative integer k less than len
such that:
this.charAt(toffset+k) != other.charAt(ooffset+k)
- ignoreCase is true and there is some nonnegative
integer k less than len such that:
Character.toLowerCase(this.charAt(toffset+k)) !=
Character.toLowerCase(other.charAt(ooffset+k))
and:
Character.toUpperCase(this.charAt(toffset+k)) !=
Character.toUpperCase(other.charAt(ooffset+k))
char ta[] = value;
int to = offset + toffset;
int tlim = offset + count;
char pa[] = other.value;
int po = other.offset + ooffset;
// Note: toffset, ooffset, or len might be near -1>>>1.
if ((ooffset < 0) || (toffset < 0) || (toffset > (long)count - len) ||
(ooffset > (long)other.count - len)) {
return false;
}
while (len-- > 0) {
char c1 = ta[to++];
char c2 = pa[po++];
if (c1 == c2)
continue;
if (ignoreCase) {
// If characters don't match but case may be ignored,
// try converting both characters to uppercase.
// If the results match, then the comparison scan should
// continue.
char u1 = Character.toUpperCase(c1);
char u2 = Character.toUpperCase(c2);
if (u1 == u2)
continue;
// Unfortunately, conversion to uppercase does not work properly
// for the Georgian alphabet, which has strange rules about case
// conversion. So we need to make one last check before
// exiting.
if (Character.toLowerCase(u1) == Character.toLowerCase(u2))
continue;
}
return false;
}
return true;
| public java.lang.String | replace(char oldChar, char newChar)Returns a new string resulting from replacing all occurrences of
oldChar in this string with newChar .
If the character oldChar does not occur in the
character sequence represented by this String object,
then a reference to this String object is returned.
Otherwise, a new String object is created that
represents a character sequence identical to the character sequence
represented by this String object, except that every
occurrence of oldChar is replaced by an occurrence
of newChar .
Examples:
"mesquite in your cellar".replace('e', 'o')
returns "mosquito in your collar"
"the war of baronets".replace('r', 'y')
returns "the way of bayonets"
"sparring with a purple porpoise".replace('p', 't')
returns "starring with a turtle tortoise"
"JonL".replace('q', 'x') returns "JonL" (no change)
if (oldChar != newChar) {
int len = count;
int i = -1;
char[] val = value; /* avoid getfield opcode */
int off = offset; /* avoid getfield opcode */
while (++i < len) {
if (val[off + i] == oldChar) {
break;
}
}
if (i < len) {
char buf[] = new char[len];
for (int j = 0 ; j < i ; j++) {
buf[j] = val[off+j];
}
while (i < len) {
char c = val[off + i];
buf[i] = (c == oldChar) ? newChar : c;
i++;
}
return new String(0, len, buf);
}
}
return this;
| public boolean | startsWith(java.lang.String prefix, int toffset)Tests if this string starts with the specified prefix beginning
at the specified index.
char ta[] = value;
int to = offset + toffset;
int tlim = offset + count;
char pa[] = prefix.value;
int po = prefix.offset;
int pc = prefix.count;
// Note: toffset might be near -1>>>1.
if ((toffset < 0) || (toffset > count - pc)) {
return false;
}
while (--pc >= 0) {
if (ta[to++] != pa[po++]) {
return false;
}
}
return true;
| public boolean | startsWith(java.lang.String prefix)Tests if this string starts with the specified prefix.
return startsWith(prefix, 0);
| public java.lang.String | substring(int beginIndex)Returns a new string that is a substring of this string. The
substring begins with the character at the specified index and
extends to the end of this string.
Examples:
"unhappy".substring(2) returns "happy"
"Harbison".substring(3) returns "bison"
"emptiness".substring(9) returns "" (an empty string)
return substring(beginIndex, count);
| public java.lang.String | substring(int beginIndex, int endIndex)Returns a new string that is a substring of this string. The
substring begins at the specified beginIndex and
extends to the character at index endIndex - 1 .
Thus the length of the substring is endIndex-beginIndex .
Examples:
"hamburger".substring(4, 8) returns "urge"
"smiles".substring(1, 5) returns "mile"
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
| public char[] | toCharArray()Converts this string to a new character array.
char result[] = new char[count];
getChars(0, count, result, 0);
return result;
| public java.lang.String | toLowerCase()Converts all of the characters in this String to lower case.
int i;
scan : {
for(i = 0 ; i < count ; i++) {
char c = value[offset+i];
if (c != Character.toLowerCase(c)) {
break scan;
}
}
return this;
}
char buf[] = new char[count];
System.arraycopy(value, offset, buf, 0, i);
for(; i < count ; i++) {
buf[i] = Character.toLowerCase(value[offset+i]);
}
return new String(0, count, buf);
| public java.lang.String | toString()This object (which is already a string!) is itself returned.
return this;
| public java.lang.String | toUpperCase()Converts all of the characters in this String to upper case.
int i;
scan : {
for(i = 0 ; i < count ; i++) {
char c = value[offset+i];
if (c != Character.toUpperCase(c)) {
break scan;
}
}
return this;
}
char buf[] = new char[count];
System.arraycopy(value, offset, buf, 0, i);
for(; i < count ; i++) {
buf[i] = Character.toUpperCase(value[offset+i]);
}
return new String(0, count, buf);
| public java.lang.String | trim()Removes white space from both ends of this string.
If this String object represents an empty character
sequence, or the first and last characters of character sequence
represented by this String object both have codes
greater than '\u0020' (the space character), then a
reference to this String object is returned.
Otherwise, if there is no character with a code greater than
'\u0020' in the string, then a new
String object representing an empty string is created
and returned.
Otherwise, let k be the index of the first character in the
string whose code is greater than '\u0020' , and let
m be the index of the last character in the string whose code
is greater than '\u0020' . A new String
object is created, representing the substring of this string that
begins with the character at index k and ends with the
character at index m-that is, the result of
this.substring(k, m+1) .
This method may be used to trim whitespace from the beginning and end
of a string; in fact, it trims all ASCII control characters as well.
int len = count;
int st = 0;
int off = offset; /* avoid getfield opcode */
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[off + st] <= ' ")) {
st++;
}
while ((st < len) && (val[off + len - 1] <= ' ")) {
len--;
}
return ((st > 0) || (len < count)) ? substring(st, len) : this;
| public static java.lang.String | valueOf(java.lang.Object obj)Returns the string representation of the Object argument.
return (obj == null) ? "null" : obj.toString();
| public static java.lang.String | valueOf(char[] data)Returns the string representation of the char array
argument. The contents of the character array are copied; subsequent
modification of the character array does not affect the newly
created string.
return new String(data);
| public static java.lang.String | valueOf(char[] data, int offset, int count)Returns the string representation of a specific subarray of the
char array argument.
The offset argument is the index of the first
character of the subarray. The count argument
specifies the length of the subarray. The contents of the subarray
are copied; subsequent modification of the character array does not
affect the newly created string.
return new String(data, offset, count);
| public static java.lang.String | valueOf(boolean b)Returns the string representation of the boolean argument.
return b ? "true" : "false";
| public static java.lang.String | valueOf(char c)Returns the string representation of the char
argument.
char data[] = {c};
return new String(0, 1, data);
| public static java.lang.String | valueOf(int i)Returns the string representation of the int argument.
The representation is exactly the one returned by the
Integer.toString method of one argument.
return Integer.toString(i, 10);
| public static java.lang.String | valueOf(long l)Returns the string representation of the long argument.
The representation is exactly the one returned by the
Long.toString method of one argument.
return Long.toString(l, 10);
| public static java.lang.String | valueOf(float f)Returns the string representation of the float argument.
The representation is exactly the one returned by the
Float.toString method of one argument.
return Float.toString(f);
| public static java.lang.String | valueOf(double d)Returns the string representation of the double argument.
The representation is exactly the one returned by the
Double.toString method of one argument.
return Double.toString(d);
|
|