java.lang
public final class String extends Object implements Serializable, Comparable<String>, CharSequence
This class also includes a number of methods for manipulating the contents of strings (of course, creating a new object if there are any changes, as String is immutable). Case mapping relies on Unicode 3.0.0 standards, where some character sequences have a different number of characters in the uppercase version than the lower case.
Strings are special, in that they are the only object with an overloaded operator. When you use '+' with at least one String argument, both arguments have String conversion performed on them, and another String (not guaranteed to be unique) results.
String is special-cased when doing data serialization - rather than listing the fields of this class, a String object is converted to a string literal in the object stream.
Modifier and Type | Field and Description |
---|---|
static Comparator<String> |
CASE_INSENSITIVE_ORDER
A Comparator that uses
String.compareToIgnoreCase(String) . |
Constructor and Description |
---|
String()
Creates an empty String (length 0).
|
String(byte[] data)
Creates a new String using the byte array.
|
String(byte[] ascii,
int hibyte)
Deprecated.
use
String(byte[], String) to perform
correct encoding |
String(byte[] data,
int offset,
int count)
Creates a new String using the portion of the byte array starting at the
offset and ending at offset + count.
|
String(byte[] ascii,
int hibyte,
int offset,
int count)
Deprecated.
use
String(byte[], int, int, String) to perform
correct encoding |
String(byte[] data,
int offset,
int count,
String encoding)
Creates a new String using the portion of the byte array starting at the
offset and ending at offset + count.
|
String(byte[] data,
String encoding)
Creates a new String using the byte array.
|
String(char[] data)
Creates a new String using the character sequence of the char array.
|
String(char[] data,
int offset,
int count)
Creates a new String using the character sequence of a subarray of
characters.
|
String(String str)
Copies the contents of a String to a new String.
|
String(StringBuffer buffer)
Creates a new String using the character sequence represented by
the StringBuffer.
|
String(StringBuilder buffer)
Creates a new String using the character sequence represented by
the StringBuilder.
|
Modifier and Type | Method and Description |
---|---|
char |
charAt(int index)
Returns the character located at the specified index within this String.
|
int |
codePointAt(int index)
Get the code point at the specified index.
|
int |
codePointBefore(int index)
Get the code point before the specified index.
|
int |
codePointCount(int start,
int end)
Return the number of code points between two indices in the
String . |
int |
compareTo(String anotherString)
Compares this String and another String (case sensitive,
lexicographically).
|
int |
compareToIgnoreCase(String str)
Compares this String and another String (case insensitive).
|
String |
concat(String str)
Concatenates a String to this String.
|
boolean |
contains(CharSequence s)
Returns true iff this String contains the sequence of Characters
described in s.
|
boolean |
contentEquals(CharSequence seq)
Compares the given CharSequence to this String.
|
boolean |
contentEquals(StringBuffer buffer)
Compares the given StringBuffer to this String.
|
static String |
copyValueOf(char[] data)
Returns a String representation of a character array.
|
static String |
copyValueOf(char[] data,
int offset,
int count)
Returns a String representing the character sequence of the char array,
starting at the specified offset, and copying chars up to the specified
count.
|
boolean |
endsWith(String suffix)
Predicate which determines if this String ends with a given suffix.
|
boolean |
equals(Object anObject)
Predicate which compares anObject to this.
|
boolean |
equalsIgnoreCase(String anotherString)
Compares a String to this String, ignoring case.
|
static String |
format(Locale locale,
String format,
Object... args) |
static String |
format(String format,
Object... args) |
byte[] |
getBytes()
Converts the Unicode characters in this String to a byte array.
|
void |
getBytes(int srcBegin,
int srcEnd,
byte[] dst,
int dstBegin)
Deprecated.
use
getBytes() , which uses a char to byte encoder |
byte[] |
getBytes(String enc)
Converts the Unicode characters in this String to a byte array.
|
void |
getChars(int srcBegin,
int srcEnd,
char[] dst,
int dstBegin)
Copies characters from this String starting at a specified start index,
ending at a specified stop index, to a character array starting at
a specified destination begin index.
|
int |
hashCode()
Computes the hashcode for this String.
|
int |
indexOf(int ch)
Finds the first instance of a character in this String.
|
int |
indexOf(int ch,
int fromIndex)
Finds the first instance of a character in this String, starting at
a given index.
|
int |
indexOf(String str)
Finds the first instance of a String in this String.
|
int |
indexOf(String str,
int fromIndex)
Finds the first instance of a String in this String, starting at
a given index.
|
String |
intern()
Fetches this String from the intern hashtable.
|
boolean |
isEmpty()
Returns true if, and only if,
length()
is 0 . |
int |
lastIndexOf(int ch)
Finds the last instance of a character in this String.
|
int |
lastIndexOf(int ch,
int fromIndex)
Finds the last instance of a character in this String, starting at
a given index.
|
int |
lastIndexOf(String str)
Finds the last instance of a String in this String.
|
int |
lastIndexOf(String str,
int fromIndex)
Finds the last instance of a String in this String, starting at
a given index.
|
int |
length()
Returns the number of characters contained in this String.
|
boolean |
matches(String regex)
Test if this String matches a regular expression.
|
int |
offsetByCodePoints(int index,
int codePointOffset)
Return the index into this String that is offset from the given index by
codePointOffset code points. |
boolean |
regionMatches(boolean ignoreCase,
int toffset,
String other,
int ooffset,
int len)
Predicate which determines if this String matches another String
starting at a specified offset for each String and continuing
for a specified length, optionally ignoring case.
|
boolean |
regionMatches(int toffset,
String other,
int ooffset,
int len)
Predicate which determines if this String matches another String
starting at a specified offset for each String and continuing
for a specified length.
|
String |
replace(char oldChar,
char newChar)
Replaces every instance of a character in this String with a new
character.
|
String |
replace(CharSequence target,
CharSequence replacement)
Returns a string that is this string with all instances of the sequence
represented by
target replaced by the sequence in
replacement . |
String |
replaceAll(String regex,
String replacement)
Replaces all matching substrings of the regular expression with a
given replacement.
|
String |
replaceFirst(String regex,
String replacement)
Replaces the first substring match of the regular expression with a
given replacement.
|
String[] |
split(String regex)
Split this string around the matches of a regular expression.
|
String[] |
split(String regex,
int limit)
Split this string around the matches of a regular expression.
|
boolean |
startsWith(String prefix)
Predicate which determines if this String starts with a given prefix.
|
boolean |
startsWith(String prefix,
int toffset)
Predicate which determines if this String contains the given prefix,
beginning comparison at toffset.
|
CharSequence |
subSequence(int begin,
int end)
Creates a substring of this String, starting at a specified index
and ending at one character before a specified index.
|
String |
substring(int begin)
Creates a substring of this String, starting at a specified index
and ending at the end of this String.
|
String |
substring(int begin,
int end)
Creates a substring of this String, starting at a specified index
and ending at one character before a specified index.
|
char[] |
toCharArray()
Copies the contents of this String into a character array.
|
String |
toLowerCase()
Lowercases this String.
|
String |
toLowerCase(Locale locale)
Lowercases this String according to a particular locale.
|
String |
toString()
Returns this, as it is already a String!
|
String |
toUpperCase()
Uppercases this String.
|
String |
toUpperCase(Locale locale)
Uppercases this String according to a particular locale.
|
String |
trim()
Trims all characters less than or equal to
' '
(' ' ) from the beginning and end of this String. |
static String |
valueOf(boolean b)
Returns a String representing a boolean.
|
static String |
valueOf(char c)
Returns a String representing a character.
|
static String |
valueOf(char[] data)
Returns a String representation of a character array.
|
static String |
valueOf(char[] data,
int offset,
int count)
Returns a String representing the character sequence of the char array,
starting at the specified offset, and copying chars up to the specified
count.
|
static String |
valueOf(double d)
Returns a String representing a double.
|
static String |
valueOf(float f)
Returns a String representing a float.
|
static String |
valueOf(int i)
Returns a String representing an integer.
|
static String |
valueOf(long l)
Returns a String representing a long.
|
static String |
valueOf(Object obj)
Returns a String representation of an Object.
|
public static final Comparator<String> CASE_INSENSITIVE_ORDER
String.compareToIgnoreCase(String)
.
This comparator is Serializable
. Note that it ignores Locale,
for that, you want a Collator.Collator.compare(String, String)
public String()
""
instead.public String(String str)
str
- String to copyNullPointerException
- if value is nullpublic String(char[] data)
data
- char array to copyNullPointerException
- if data is nullpublic String(char[] data, int offset, int count)
data
- char array to copyoffset
- position (base 0) to start copying out of datacount
- the number of characters from data to copyNullPointerException
- if data is nullIndexOutOfBoundsException
- if (offset < 0 || count < 0
|| offset + count < 0 (overflow)
|| offset + count > data.length)
(while unspecified, this is a StringIndexOutOfBoundsException)public String(byte[] ascii, int hibyte, int offset, int count)
String(byte[], int, int, String)
to perform
correct encodingc = (char) (((hibyte & 0xff) << 8) | (b & 0xff))
ascii
- array of integer valueshibyte
- top byte of each Unicode characteroffset
- position (base 0) to start copying out of asciicount
- the number of characters from ascii to copyNullPointerException
- if ascii is nullIndexOutOfBoundsException
- if (offset < 0 || count < 0
|| offset + count < 0 (overflow)
|| offset + count > ascii.length)
(while unspecified, this is a StringIndexOutOfBoundsException)String(byte[])
,
String(byte[], String)
,
String(byte[], int, int)
,
String(byte[], int, int, String)
public String(byte[] ascii, int hibyte)
String(byte[], String)
to perform
correct encodingc = (char) (((hibyte & 0xff) << 8) | (b & 0xff))
ascii
- array of integer valueshibyte
- top byte of each Unicode characterNullPointerException
- if ascii is nullString(byte[])
,
String(byte[], String)
,
String(byte[], int, int)
,
String(byte[], int, int, String)
,
String(byte[], int, int, int)
public String(byte[] data, int offset, int count, String encoding) throws UnsupportedEncodingException
CharsetDecoder
, and for valid character sets,
see Charset
. The behavior is not specified if
the decoder encounters invalid characters; this implementation throws
an Error.data
- byte array to copyoffset
- the offset to start atcount
- the number of bytes in the array to useencoding
- the name of the encoding to useNullPointerException
- if data or encoding is nullIndexOutOfBoundsException
- if offset or count is incorrect
(while unspecified, this is a StringIndexOutOfBoundsException)UnsupportedEncodingException
- if encoding is not foundError
- if the decoding failspublic String(byte[] data, String encoding) throws UnsupportedEncodingException
CharsetDecoder
, and for valid character sets,
see Charset
. The behavior is not specified if
the decoder encounters invalid characters; this implementation throws
an Error.data
- byte array to copyencoding
- the name of the encoding to useNullPointerException
- if data or encoding is nullUnsupportedEncodingException
- if encoding is not foundError
- if the decoding failsString(byte[], int, int, String)
public String(byte[] data, int offset, int count)
CharsetDecoder
. The behavior is not specified
if the decoder encounters invalid characters; this implementation throws
an Error.data
- byte array to copyoffset
- the offset to start atcount
- the number of bytes in the array to useNullPointerException
- if data is nullIndexOutOfBoundsException
- if offset or count is incorrectError
- if the decoding failsString(byte[], int, int, String)
public String(byte[] data)
CharsetDecoder
. The behavior is not specified
if the decoder encounters invalid characters; this implementation throws
an Error.data
- byte array to copyNullPointerException
- if data is nullError
- if the decoding failsString(byte[], int, int)
,
String(byte[], int, int, String)
public String(StringBuffer buffer)
buffer
- StringBuffer to copyNullPointerException
- if buffer is nullpublic String(StringBuilder buffer)
buffer
- StringBuilder to copyNullPointerException
- if buffer is nullpublic int length()
length
in interface CharSequence
public char charAt(int index)
charAt
in interface CharSequence
index
- position of character to return (base 0)IndexOutOfBoundsException
- if index < 0 || index >= length()
(while unspecified, this is a StringIndexOutOfBoundsException)public int codePointAt(int index)
index
- the index of the codepoint to get, starting at 0IndexOutOfBoundsException
- if index is negative or >= length()public int codePointBefore(int index)
index-1
and
index-2
to see if they form a supplementary code point.index
- the index just past the codepoint to get, starting at 0IndexOutOfBoundsException
- if index is negative or >= length()
(while unspecified, this is a StringIndexOutOfBoundsException)public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
srcBegin
- index to begin copying characters from this StringsrcEnd
- index after the last character to be copied from this Stringdst
- character array which this String is copied intodstBegin
- index to start writing characters into dstNullPointerException
- if dst is nullIndexOutOfBoundsException
- if any indices are out of bounds
(while unspecified, source problems cause a
StringIndexOutOfBoundsException, and dst problems cause an
ArrayIndexOutOfBoundsException)public void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)
getBytes()
, which uses a char to byte encodersrcBegin
- index to being copying characters from this StringsrcEnd
- index after the last character to be copied from this Stringdst
- byte array which each low byte of this String is copied intodstBegin
- index to start writing characters into dstNullPointerException
- if dst is null and copy length is non-zeroIndexOutOfBoundsException
- if any indices are out of bounds
(while unspecified, source problems cause a
StringIndexOutOfBoundsException, and dst problems cause an
ArrayIndexOutOfBoundsException)getBytes()
,
getBytes(String)
public byte[] getBytes(String enc) throws UnsupportedEncodingException
CharsetEncoder
, and for valid character sets,
see Charset
. The behavior is not specified if
the encoder encounters a problem; this implementation returns null.enc
- encoding nameNullPointerException
- if enc is nullUnsupportedEncodingException
- if encoding is not supportedpublic byte[] getBytes()
CharsetEncoder
. The behavior is not specified if
the encoder encounters a problem; this implementation returns null.public boolean equals(Object anObject)
equals
in class Object
anObject
- the object to comparecompareTo(String)
,
equalsIgnoreCase(String)
public boolean contentEquals(StringBuffer buffer)
buffer
- the StringBuffer to compare toNullPointerException
- if the given StringBuffer is nullpublic boolean contentEquals(CharSequence seq)
seq
- the CharSequence to compare toNullPointerException
- if the given CharSequence is nullpublic boolean equalsIgnoreCase(String anotherString)
c1 == c2
Character.toUpperCase(c1)
== Character.toUpperCase(c2)
Character.toLowerCase(c1)
== Character.toLowerCase(c2)
anotherString
- String to compare to this Stringequals(Object)
,
Character.toUpperCase(char)
,
Character.toLowerCase(char)
public int compareTo(String anotherString)
this.charAt(k) - anotherString.charAt(k)
if both strings
have characters remaining, or
this.length() - anotherString.length()
if one string is
a subsequence of the other.compareTo
in interface Comparable<String>
anotherString
- the String to compare againstNullPointerException
- if anotherString is nullpublic int compareToIgnoreCase(String str)
Character.toLowerCase(Character.toUpperCase(c))
on each
character of the string. This is unsatisfactory for locale-based
comparison, in which case you should use Collator
.str
- the string to compare againstCollator.compare(String, String)
public boolean regionMatches(int toffset, String other, int ooffset, int len)
toffset
- index to start comparison at for this Stringother
- String to compare region to this Stringooffset
- index to start comparison at for otherlen
- number of characters to compareNullPointerException
- if other is nullpublic boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Character.toLowerCase()
and
Character.toUpperCase()
, not on multi-character
capitalization expansions.ignoreCase
- true if case should be ignored in comparisiontoffset
- index to start comparison at for this Stringother
- String to compare region to this Stringooffset
- index to start comparison at for otherlen
- number of characters to compareNullPointerException
- if other is nullpublic boolean startsWith(String prefix, int toffset)
this.substring(toffset).startsWith(prefix)
.prefix
- String to comparetoffset
- offset for this String where comparison startsNullPointerException
- if prefix is nullregionMatches(boolean, int, String, int, int)
public boolean startsWith(String prefix)
prefix
- String to compareNullPointerException
- if prefix is nullstartsWith(String, int)
public boolean endsWith(String suffix)
suffix
- String to compareNullPointerException
- if suffix is nullregionMatches(boolean, int, String, int, int)
public int hashCode()
s[0]*31**(n-1) + s[1]*31**(n-2) + ... + s[n-1]
.hashCode
in class Object
Object.equals(Object)
,
System.identityHashCode(Object)
public int indexOf(int ch)
ch
- character to findpublic int indexOf(int ch, int fromIndex)
ch
- character to findfromIndex
- index to start the searchpublic int lastIndexOf(int ch)
ch
- character to findpublic int lastIndexOf(int ch, int fromIndex)
ch
- character to findfromIndex
- index to start the searchpublic int indexOf(String str)
str
- String to findNullPointerException
- if str is nullpublic int indexOf(String str, int fromIndex)
str
- String to findfromIndex
- index to start the searchNullPointerException
- if str is nullpublic int lastIndexOf(String str)
str
- String to findNullPointerException
- if str is nullpublic int lastIndexOf(String str, int fromIndex)
str
- String to findfromIndex
- index to start the searchNullPointerException
- if str is nullpublic String substring(int begin)
begin
- index to start substring (base 0)IndexOutOfBoundsException
- if begin < 0 || begin > length()
(while unspecified, this is a StringIndexOutOfBoundsException)public String substring(int begin, int end)
begin
- index to start substring (inclusive, base 0)end
- index to end at (exclusive)IndexOutOfBoundsException
- if begin < 0 || end > length()
|| begin > end (while unspecified, this is a
StringIndexOutOfBoundsException)public CharSequence subSequence(int begin, int end)
substring(begin, end)
.subSequence
in interface CharSequence
begin
- index to start substring (inclusive, base 0)end
- index to end at (exclusive)IndexOutOfBoundsException
- if begin < 0 || end > length()
|| begin > endpublic String concat(String str)
str
- String to append to this StringNullPointerException
- if str is nullpublic String replace(char oldChar, char newChar)
oldChar
- the old character to replacenewChar
- the new characterpublic boolean matches(String regex)
Pattern
.matches(regex, this)
.regex
- the pattern to matchNullPointerException
- if regex is nullPatternSyntaxException
- if regex is invalidPattern.matches(String, CharSequence)
public String replaceFirst(String regex, String replacement)
Pattern
.compile(regex).matcher(this).replaceFirst(replacement)
.regex
- the pattern to matchreplacement
- the replacement stringNullPointerException
- if regex or replacement is nullPatternSyntaxException
- if regex is invalidreplaceAll(String, String)
,
Pattern.compile(String)
,
Pattern.matcher(CharSequence)
,
Matcher.replaceFirst(String)
public String replaceAll(String regex, String replacement)
Pattern
.compile(regex).matcher(this).replaceAll(replacement)
.regex
- the pattern to matchreplacement
- the replacement stringNullPointerException
- if regex or replacement is nullPatternSyntaxException
- if regex is invalidreplaceFirst(String, String)
,
Pattern.compile(String)
,
Pattern.matcher(CharSequence)
,
Matcher.replaceAll(String)
public String[] split(String regex, int limit)
The limit affects the length of the array. If it is positive, the array will contain at most n elements (n - 1 pattern matches). If negative, the array length is unlimited, but there can be trailing empty entries. if 0, the array length is unlimited, and trailing empty entries are discarded.
For example, splitting "boo:and:foo" yields:
Regex | Limit | Result |
":" | 2 | { "boo", "and:foo" } |
":" | t | { "boo", "and", "foo" } |
":" | -2 | { "boo", "and", "foo" } |
"o" | 5 | { "b", "", ":and:f", "", "" } |
"o" | -2 | { "b", "", ":and:f", "", "" } |
"o" | 0 | { "b", "", ":and:f" } |
This is shorthand for
.Pattern
.compile(regex).split(this, limit)
regex
- the pattern to matchlimit
- the limit thresholdNullPointerException
- if regex or replacement is nullPatternSyntaxException
- if regex is invalidPattern.compile(String)
,
Pattern.split(CharSequence, int)
public String[] split(String regex)
split(regex, 0)
.regex
- the pattern to matchNullPointerException
- if regex or replacement is nullPatternSyntaxException
- if regex is invalidsplit(String, int)
,
Pattern.compile(String)
,
Pattern.split(CharSequence, int)
public String toLowerCase(Locale locale)
loc
- locale to useNullPointerException
- if loc is nulltoUpperCase(Locale)
public String toLowerCase()
toLowerCase(Locale)
,
toUpperCase()
public String toUpperCase(Locale locale)
loc
- locale to useNullPointerException
- if loc is nulltoLowerCase(Locale)
public String toUpperCase()
toUpperCase(Locale)
,
toLowerCase()
public String trim()
' '
(' '
) from the beginning and end of this String. This
includes many, but not all, ASCII control characters, and all
Character.isWhitespace(char)
.public String toString()
toString
in interface CharSequence
toString
in class Object
Object.getClass()
,
Object.hashCode()
,
Class.getName()
,
Integer.toHexString(int)
public char[] toCharArray()
public static String valueOf(Object obj)
obj.toString()
(which
can be null).obj
- the Objectpublic static String valueOf(char[] data)
data
- the character arrayNullPointerException
- if data is nullvalueOf(char[], int, int)
,
String(char[])
public static String valueOf(char[] data, int offset, int count)
data
- character arrayoffset
- position (base 0) to start copying out of datacount
- the number of characters from data to copyNullPointerException
- if data is nullIndexOutOfBoundsException
- if (offset < 0 || count < 0
|| offset + count > data.length)
(while unspecified, this is a StringIndexOutOfBoundsException)String(char[], int, int)
public static String copyValueOf(char[] data, int offset, int count)
data
- character arrayoffset
- position (base 0) to start copying out of datacount
- the number of characters from data to copyNullPointerException
- if data is nullIndexOutOfBoundsException
- if (offset < 0 || count < 0
|| offset + count < 0 (overflow)
|| offset + count > data.length)
(while unspecified, this is a StringIndexOutOfBoundsException)String(char[], int, int)
public static String copyValueOf(char[] data)
data
- the character arrayNullPointerException
- if data is nullcopyValueOf(char[], int, int)
,
String(char[])
public static String valueOf(boolean b)
b
- the booleanpublic static String valueOf(char c)
c
- the characterpublic static String valueOf(int i)
i
- the integerInteger.toString(int)
public static String valueOf(long l)
l
- the longLong.toString(long)
public static String valueOf(float f)
f
- the floatFloat.toString(float)
public static String valueOf(double d)
d
- the doubleDouble.toString(double)
public String intern()
public int codePointCount(int start, int end)
String
. An unpaired surrogate counts as a
code point for this purpose. Characters outside the indicated
range are not examined, even if the range ends in the middle of a
surrogate pair.start
- the starting indexend
- one past the ending indexpublic boolean contains(CharSequence s)
s
- the CharSequencepublic String replace(CharSequence target, CharSequence replacement)
target
replaced by the sequence in
replacement
.target
- the sequence to be replacedreplacement
- the sequence used as the replacementpublic int offsetByCodePoints(int index, int codePointOffset)
codePointOffset
code points.index
- the index at which to startcodePointOffset
- the number of code points to offsetcodePointOffset
code points offset from index
.IndexOutOfBoundsException
- if index is negative or larger than the
length of this string.IndexOutOfBoundsException
- if codePointOffset is positive and the
substring starting with index has fewer than codePointOffset code points.IndexOutOfBoundsException
- if codePointOffset is negative and the
substring ending with index has fewer than (-codePointOffset) code points.