public final class String extends Object implements Serializable, Comparable<String>, CharSequence
Supplementary characters are represented by pairs of 16-bit char values (surrogate pairs), i.e., UTF-16 encoding is used. Strings provide access to the single 16-bit char in the UTF-16 string, but also to the unicode code points.
Modifier and Type | Field and Description |
---|---|
static Comparator<String> |
CASE_INSENSITIVE_ORDER
A comparator that is based on compareToIgnoreCase to order
strings.
|
Constructor and Description |
---|
String()
Constructor for an empty string.
|
String(byte[] bytes)
Constructs a new
String by decoding the specified array of bytes
using the platform's default charset. |
String(byte[] bytes,
Charset charset)
Constructs a new
String by decoding the specified array of
bytes using the specified charset. |
String(byte[] ascii,
int hibyte)
Deprecated.
This method does not properly convert bytes into
characters. As of JDK 1.1, the preferred way to do this is via the
String constructors that take a Charset , charset name, or that use the platform's
default charset. |
String(byte[] bytes,
int offset,
int length)
Constructs a new
String by decoding the specified subarray of
bytes using the platform's default charset. |
String(byte[] bytes,
int offset,
int length,
Charset charset)
Constructs a new
String by decoding the specified subarray of
bytes using the specified charset. |
String(byte[] ascii,
int hibyte,
int offset,
int count)
Deprecated.
This method does not properly convert bytes into characters.
As of JDK 1.1, the preferred way to do this is via the
String constructors that take a Charset , charset name, or that use the platform's
default charset. |
String(byte[] bytes,
int offset,
int length,
String charsetName)
Constructs a new
String by decoding the specified subarray of
bytes using the specified charset. |
String(byte[] bytes,
String charsetName)
Constructs a new
String by decoding the specified array of bytes
using the specified charset. |
String(char[] value)
Constructor for a string that contains the characters of a given
character array.
|
String(char[] value,
int offset,
int count)
Allocates a new
String that contains characters from a subarray
of the character array argument. |
String(int[] codePoints,
int offset,
int count)
Allocates a new
String that contains characters from a subarray
of the Unicode code point array
argument. |
String(String str)
Constructor for a copy of a string.
|
String(StringBuffer sb)
Constructor that creates a String object from the characters in a
StringBuffer.
|
String(StringBuilder sb)
Constructor that creates a String object from the characters in a
StringBuilder.
|
Modifier and Type | Method and Description |
---|---|
char |
charAt(int index)
charAt returns the 16-bit character at the given index of this
String.
|
int |
codePointAt(int index)
codePointAt
|
int |
codePointBefore(int index)
codePointBefore
|
int |
codePointCount(int beginIndex,
int endIndex)
codePointCount
|
int |
compareTo(String str)
compareTo compares two strings lexicographically.
|
int |
compareToIgnoreCase(String str)
compareTo compares two strings lexicographically ignoring
case.
|
String |
concat(String str)
concat creates a String that contains the concatenation of this
string and another string.
|
boolean |
contains(CharSequence s)
Returns true if and only if this string contains the specified
sequence of char values.
|
boolean |
contentEquals(CharSequence cs)
Compares this string to the specified
CharSequence . |
boolean |
contentEquals(StringBuffer sb)
Compares this string to the specified
StringBuffer . |
static String |
copyValueOf(char[] data)
copyValueOf returns a String containing the characters of the
given character array.
|
static String |
copyValueOf(char[] data,
int offset,
int count)
copyValueOf creates a String that contains a subrange of the
characters of a given character array.
|
boolean |
endsWith(String suffix)
Check if this string ends with the given suffix.
|
boolean |
equals(Object o)
Compare this String to another String.
|
boolean |
equalsIgnoreCase(String str)
Compare this String to another String ignoring case.
|
static String |
format(Locale l,
String format,
Object... args)
Returns a formatted string using the specified locale, format string,
and arguments.
|
static String |
format(String format,
Object... args)
Returns a formatted string using the specified format string and
arguments.
|
byte[] |
getBytes()
getBytes converts the characters of this String to a sequence of
bytes using the default encoding.
|
byte[] |
getBytes(Charset encoding)
Encodes this
String into a sequence of bytes using the given
charset, storing the result into a
new byte array. |
void |
getBytes(int srcBegin,
int srcEnd,
byte[] dst,
int dstBegin)
Deprecated.
This method does not use the proper encoding. Use
getBytes() to use the default encoding.
|
byte[] |
getBytes(String charsetName)
Encodes this
String into a sequence of bytes using the named
charset, storing the result into a new byte array. |
void |
getChars(int srcBegin,
int srcEnd,
char[] dst,
int dstBegin)
getChars copies a subrange of the the characters of this string
into a character array.
|
int |
hashCode()
hashCode calculates a hash code for this string.
|
int |
indexOf(int ch)
Find the first index of a given character or code point.
|
int |
indexOf(int ch,
int from)
Find the first index of a given character or code point starting
from a given findex.
|
int |
indexOf(String str)
Return the index of the first substring of this that is equal to
str.
|
int |
indexOf(String str,
int from)
Return the index of the first substring of this that is equal to
str and that start at from or later.
|
protected int |
indexOfCharSequence(CharSequence s,
int from)
Return the index of the first occurrence of a substring this that
is equal to a CharSequence and that starts at from or later.
|
String |
intern()
intern interns this String.
|
boolean |
isEmpty()
Returns true if, and only if,
length() is 0. |
static String |
join(CharSequence delimiter,
CharSequence... elements)
Returns a new String composed of copies of the
CharSequence elements joined together with a copy of
the specified delimiter . |
static String |
join(CharSequence delimiter,
Iterable<? extends CharSequence> elements)
Returns a new
String composed of copies of the
CharSequence elements joined together with a copy of the
specified delimiter . |
int |
lastIndexOf(int ch)
Find the last index of a given character or code point.
|
int |
lastIndexOf(int ch,
int from)
Find the last index of a given character or code point starting
from a given findex.
|
int |
lastIndexOf(String str)
Return the index of the last substring of this that is equal to
str.
|
int |
lastIndexOf(String str,
int from)
Return the index of the last substring of this that is equal to
str and that is before a given index.
|
int |
length()
length returns the length of this string, i.e., the number of
16-bit characters contained in this string.
|
boolean |
matches(String regex)
Tells whether or not this string matches the given regular expression.
|
int |
offsetByCodePoints(int index,
int codePointOffset)
offsetByCodePoints
|
boolean |
regionMatches(boolean ignoreCase,
int offset,
String other,
int ooffset,
int len)
Compare a region of this string with another string, optionally
ignoring case.
|
boolean |
regionMatches(int offset,
String other,
int ooffset,
int len)
Compare a region of this string with another string.
|
String |
replace(char oldChar,
char newChar)
replace creates a new String that is equal to this String with a
given character replaced by another character.
|
String |
replace(CharSequence target,
CharSequence replacement)
Replaces each substring of this string that matches the literal target
sequence with the specified literal replacement sequence.
|
String |
replaceAll(String regex,
String replacement)
Replaces each substring of this string that matches the given regular expression with the
given replacement.
|
String |
replaceFirst(String regex,
String replacement)
Replaces the first substring of this string that matches the given regular expression with the
given replacement.
|
String[] |
split(String regex)
Splits this string around matches of the given regular expression.
|
String[] |
split(String regex,
int limit)
Splits this string around matches of the given
regular expression.
|
boolean |
startsWith(String prefix)
Check if this string starts with the given prefix.
|
boolean |
startsWith(String prefix,
int offset)
Check if this string starts with the given prefix from the given offset.
|
CharSequence |
subSequence(int start,
int end)
subSequence creates a subsequence of this sequence.
|
String |
substring(int from)
Create a new String object with the contents of the suffix of this
String starting at a given index.
|
String |
substring(int from,
int end)
Create a new String objects with the contents of the substring of
this String.
|
char[] |
toCharArray()
toCharArray allocates a new character array and copies the
characters of this String into the array.
|
String |
toLowerCase()
toLowerCase converts this String to lower case using the default
locale.
|
String |
toLowerCase(Locale locale)
Converts all of the characters in this
String to lower
case using the rules of the given Locale . |
String |
toString()
toString creates a printable string that represents this object
for debugging purposes.
|
String |
toUpperCase()
toUpperCase converts this String to lower case using the default
locale.
|
String |
toUpperCase(Locale locale)
Converts all of the characters in this
String to upper
case using the rules of the given Locale . |
String |
trim()
trim removes all leading and trailing characters with a code <=
' ' from this String.
|
static String |
valueOf(boolean b)
valueOf converts a boolean to a String.
|
static String |
valueOf(char c)
valueOf creates a one-character string containing the given
character.
|
static String |
valueOf(char[] data)
valueOf returns a String containing the characters of the given
character array.
|
static String |
valueOf(char[] data,
int offset,
int count)
valueOf creates a String that contains a subrange of the
characters of a given character array.
|
static String |
valueOf(double d)
valueOf converts a double to a String
|
static String |
valueOf(float f)
valueOf converts a float to a String
|
static String |
valueOf(int i)
valueOf converts an int to a String.
|
static String |
valueOf(long l)
valueOf converts a long to a String
|
static String |
valueOf(Object obj)
valueOf returns a String created from a given object or null.
|
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
chars, codePoints
public static final Comparator<String> CASE_INSENSITIVE_ORDER
This comparator is serializable.
public String()
A more efficient way to obtain an empty string is by using the string constant "". Using this constructor will always create a new instance, i.e., perform a memory allocation.
public String(String str)
Using this constructor will always create a new instance, i.e., perform a memory allocation. Unless a different instance is required, copying of a string is not needed.
NullPointerException
- if str is null.str
- string to copypublic String(char[] value)
ensure
( length() == value.length && for i in 0..value.length-1: charAt(i) == value[i])
NullPointerException
- if value is null.value
- character arraypublic String(char[] value, int offset, int count)
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.IndexOutOfBoundsException
- If the offset
and count
arguments index
characters outside the bounds of the value
arrayvalue
- Array that is the source of charactersoffset
- The initial offsetcount
- The lengthpublic String(int[] codePoints, int offset, int count)
String
that contains characters from a subarray
of the Unicode code point array
argument. The offset
argument is the index of the first code
point of the subarray and the count
argument specifies the
length of the subarray. The contents of the subarray are converted to
char
s; subsequent modification of the int
array does not
affect the newly created string.IllegalArgumentException
- If any invalid Unicode code point is found in codePoints
IndexOutOfBoundsException
- If the offset
and count
arguments index
characters outside the bounds of the codePoints
arraycodePoints
- Array that is the source of Unicode code pointsoffset
- The initial offsetcount
- The length@Deprecated public String(byte[] ascii, int hibyte, int offset, int count)
String
constructors that take a Charset
, charset name, or that use the platform's
default charset.String
constructed from a subarray of an array
of 8-bit integer values.
The offset
argument is the index of the first byte of the
subarray, and the count
argument specifies the length of the
subarray.
Each byte
in the subarray is converted to a char
as
specified in the method above.
IndexOutOfBoundsException
- If the offset
or count
argument is invalidascii
- The bytes to be converted to charactershibyte
- The top 8 bits of each 16-bit Unicode code unitoffset
- The initial offsetcount
- The lengthString(byte[], int)
,
String(byte[], int, int, java.lang.String)
,
String(byte[], int, int, java.nio.charset.Charset)
,
String(byte[], int, int)
,
String(byte[], java.lang.String)
,
String(byte[], java.nio.charset.Charset)
,
String(byte[])
@Deprecated public String(byte[] ascii, int hibyte)
String
constructors that take a Charset
, charset name, or that use the platform's
default charset.String
containing characters constructed from
an array of 8-bit integer values. Each character cin the
resulting string is constructed from the corresponding component
b in the byte array such that:
c == (char)(((hibyte & 0xff) << 8) | (b & 0xff))
ascii
- The bytes to be converted to charactershibyte
- The top 8 bits of each 16-bit Unicode code unitString(byte[], int, int, java.lang.String)
,
String(byte[], int, int, java.nio.charset.Charset)
,
String(byte[], int, int)
,
String(byte[], java.lang.String)
,
String(byte[], java.nio.charset.Charset)
,
String(byte[])
public String(byte[] bytes, int offset, int length, String charsetName) throws UnsupportedEncodingException
String
by decoding the specified subarray of
bytes using the specified charset. The length of the new String
is a function of the charset, and hence may not be equal to the length
of the subarray.
The behavior of this constructor when the given bytes are not valid
in the given charset is unspecified. The CharsetDecoder
class should be used when more control
over the decoding process is required.
UnsupportedEncodingException
- If the named charset is not supportedIndexOutOfBoundsException
- If the offset
and length
arguments index
characters outside the bounds of the bytes
arraybytes
- The bytes to be decoded into charactersoffset
- The index of the first byte to decodelength
- The number of bytes to decodecharsetName
- The name of a supported charsetpublic String(byte[] bytes, int offset, int length, Charset charset)
String
by decoding the specified subarray of
bytes using the specified charset.
The length of the new String
is a function of the charset, and
hence may not be equal to the length of the subarray.
This method always replaces malformed-input and unmappable-character
sequences with this charset's default replacement string. The CharsetDecoder
class should be used when more control
over the decoding process is required.
IndexOutOfBoundsException
- If the offset
and length
arguments index
characters outside the bounds of the bytes
arraybytes
- The bytes to be decoded into charactersoffset
- The index of the first byte to decodelength
- The number of bytes to decodecharset
- The charset to be used to
decode the bytes
public String(byte[] bytes, String charsetName) throws UnsupportedEncodingException
String
by decoding the specified array of bytes
using the specified charset. The
length of the new String
is a function of the charset, and hence
may not be equal to the length of the byte array.
The behavior of this constructor when the given bytes are not valid
in the given charset is unspecified. The CharsetDecoder
class should be used when more control
over the decoding process is required.
UnsupportedEncodingException
- If the named charset is not supportedbytes
- The bytes to be decoded into characterscharsetName
- The name of a supported charsetpublic String(byte[] bytes, Charset charset)
String
by decoding the specified array of
bytes using the specified charset.
The length of the new String
is a function of the charset, and
hence may not be equal to the length of the byte array.
This method always replaces malformed-input and unmappable-character
sequences with this charset's default replacement string. The CharsetDecoder
class should be used when more control
over the decoding process is required.
bytes
- The bytes to be decoded into characterscharset
- The charset to be used to
decode the bytes
public String(byte[] bytes, int offset, int length)
String
by decoding the specified subarray of
bytes using the platform's default charset. The length of the new
String
is a function of the charset, and hence may not be equal
to the length of the subarray.
The behavior of this constructor when the given bytes are not valid
in the default charset is unspecified. The CharsetDecoder
class should be used when more control
over the decoding process is required.
IndexOutOfBoundsException
- If the offset
and the length
arguments index
characters outside the bounds of the bytes
arraybytes
- The bytes to be decoded into charactersoffset
- The index of the first byte to decodelength
- The number of bytes to decodepublic String(byte[] bytes)
String
by decoding the specified array of bytes
using the platform's default charset. The length of the new String
is a function of the charset, and hence may not be equal to the
length of the byte array.
The behavior of this constructor when the given bytes are not valid
in the default charset is unspecified. The CharsetDecoder
class should be used when more control
over the decoding process is required.
bytes
- The bytes to be decoded into characterspublic String(StringBuffer sb)
ensure
( length() == sb.length() && for i in 0..length()-1: charAt(i) == sb.charAt(i))
NullPointerException
- if sb is null.sb
- the string buffer to take the characters frompublic String(StringBuilder sb)
ensure
( length() == sb.length() && for i in 0..length()-1: charAt(i) == sb.charAt(i))
NullPointerException
- if sb is null.sb
- the string builder to take the characters frompublic int length()
ensure
(result >= 0)
length
in interface CharSequence
public char charAt(int index)
implemented in C for better performance.
charAt
in interface CharSequence
IndexOutOfBoundsException
- if index<0 or index >=
length().index
- the position of the character to the readpublic int codePointAt(int index)
index
- public int codePointBefore(int index)
index
- public int codePointCount(int beginIndex, int endIndex)
beginIndex
- endIndex
- public int offsetByCodePoints(int index, int codePointOffset)
index
- codePointOffset
- public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
ensure
(for i in 0..srcEnd-srcBegin-1: charAt(srcBegin+i) == dst[dstBegin+i])
IndexOutOfBoundsException
- if srcBegin<0, srcBegin>srcEnd,
srcEnd > length(), dstBegin<0 or dstBegin+srcEnd-srcBegin >
dst.length;NullPointerException
- if dst is nullsrcBegin
- the index of the first character to copysrcEnd
- the index of the last character to copydst
- (out!) the target character arraydstBegin
- the index in the target array at which the first character should be stored.@Deprecated public void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)
ensure
(for i in 0..srcEnd-srcBegin-1: (charAt(srcBegin+i)&0xff) == (dst[dstBegin+i]&0xff))
IndexOutOfBoundsException
- if srcBegin<0, srcBegin>srcEnd,
srcEnd > length(), dstBegin<0 or dstBegin+srcEnd-srcBegin >
dst.length;NullPointerException
- if dst is nullsrcBegin
- the index of the first character to copysrcEnd
- the index of the last character to copydst
- (out!) the target byte arraydstBegin
- the index in the target array at which the first character should be stored.public byte[] getBytes(String charsetName) throws UnsupportedEncodingException
String
into a sequence of bytes using the named
charset, storing the result into a new byte array.
The behavior of this method when this string cannot be encoded in
the given charset is unspecified. The CharsetEncoder
class should be used when more control
over the encoding process is required.
UnsupportedEncodingException
- If the named charset is not supportedcharsetName
- The name of a supported charsetpublic byte[] getBytes()
Characters that cannot be encoded with the default encoding will be replaced by '?'.
For JamaicaVM, the default encoding is ISO 8859-1.
public byte[] getBytes(Charset encoding)
String
into a sequence of bytes using the given
charset, storing the result into a
new byte array.
This method always replaces malformed-input and unmappable-character
sequences with this charset's default replacement byte array. The
CharsetEncoder
class should be used when more
control over the encoding process is required.
encoding
- The Charset to be used to encode
the String
public boolean equals(Object o)
ensure
(result == ( (anObject instanceof String) && (length() == ((String)o).length()) && (for all i in 0..length()-1: charAt(i) == ((String)o).charAt(i)))
implemented in C for better performance.
equals
in class Object
o
- objectObject.hashCode()
,
HashMap
public boolean contentEquals(StringBuffer sb)
StringBuffer
. The result
is true
if and only if this String
represents the same
sequence of characters as the specified StringBuffer
. This method
synchronizes on the StringBuffer
.sb
- The StringBuffer
to compare this String
againsttrue
if this String
represents the same
sequence of characters as the specified StringBuffer
,
false
otherwisepublic boolean contentEquals(CharSequence cs)
CharSequence
. The
result is true
if and only if this String
represents the
same sequence of char values as the specified sequence. Note that if the
CharSequence
is a StringBuffer
then the method
synchronizes on it.cs
- The sequence to compare this String
againsttrue
if this String
represents the same
sequence of char values as the specified sequence, false
otherwisepublic boolean equalsIgnoreCase(String str)
(c1 == c2) || Character.toUpperCase(c1) == Character.toUpperCase(c2) || Character.toLowerCase(c1) == Character.toLowerCase(c2)
str
- the string to compare topublic int compareTo(String str)
implemented in C for better performance.
compareTo
in interface Comparable<String>
NullPointerException
- if str==nullstr
- a string to compare to.public int compareToIgnoreCase(String str)
Case is ignored by converting each character c via nested calls to Character.toLowerCase(Character.toUpperCase(c)) before the comparison.
NullPointerException
- if str==nullstr
- a string to compare to.public boolean regionMatches(int offset, String other, int ooffset, int len)
NullPointerException
- if other is null.offset
- the index in this at which comparison should start.other
- the other String to compare withooffset
- the index in other at which comparison should
start.len
- the number of characters to compare.public boolean regionMatches(boolean ignoreCase, int offset, String other, int ooffset, int len)
(c1 == c2) || Character.toUpperCase(c1) == Character.toUpperCase(c2) || Character.toLowerCase(c1) == Character.toLowerCase(c2)
NullPointerException
- if other is null.ignoreCase
- true to ignore case, false to compare
characters directly.offset
- the index in this at which comparison should start.other
- the other String to compare withooffset
- the index in other at which comparison should
start.len
- the number of characters to compare.public boolean startsWith(String prefix, int offset)
NullPointerException
- if prefix is null.prefix
- the prefixoffset
- the offset in this where to start looking for the prefixpublic boolean startsWith(String prefix)
NullPointerException
- if prefix is null.prefix
- the prefixpublic boolean endsWith(String suffix)
NullPointerException
- if suffix is null.suffix
- the suffixpublic int hashCode()
charAt(0)*31**(length()-1) + charAt(1)*31**(length()-2) + ... + charAt(length()-1)
implemented in C for better performance.
hashCode
in class Object
Object.equals(java.lang.Object)
,
System.identityHashCode(java.lang.Object)
public int indexOf(int ch)
ensure
( ((ch <= 0xffff && result == -1) IMPLIES for all i=0..length()-1: charAt(i) != ch) && ((ch <= 0xffff && result != -1) IMPLIES ( (charAt(result) == ch) && for all i=0..result-1: charAt(i) != ch)) && ((ch > 0xffff && result == -1) IMPLIES for all codepoint indices i: codePointAt(i) != ch) && ((ch > 0xffff && result != -1) IMPLIES ( (codePointAt(result) == ch) && for all i=0..result-1: codePointAt(i) != ch)
ch
- the character or code pointpublic int indexOf(int ch, int from)
ensure
( ((ch <= 0xffff && result == -1) IMPLIES for all i=from..length()-1: charAt(i) != ch) && ((ch <= 0xffff && result != -1) IMPLIES ( (charAt(result) == ch) && for all i=from..result-1: charAt(i) != ch)) && ((ch > 0xffff && result == -1) IMPLIES for all codepoint indices i: codePointAt(i) != ch) && ((ch > 0xffff && result != -1) IMPLIES ( (codePointAt(result) == ch) && for all i=from..result-1: codePointAt(i) != ch)
ch
- the character or code pointpublic int lastIndexOf(int ch)
ensure
( ((ch <= 0xffff && result == -1) IMPLIES for all i=0..length()-1: charAt(i) != ch) && ((ch <= 0xffff && result != -1) IMPLIES ( (charAt(result) == ch) && for all i=result+1..length()-1: charAt(i) != ch)) && ((ch > 0xffff && result == -1) IMPLIES for all codepoint indices i: codePointAt(i) != ch) && ((ch > 0xffff && result != -1) IMPLIES ( (codePointAt(result) == ch) && for all codepoint indices in i=result+1..length()-1: codePointAt(i) != ch)
ch
- the character or code pointpublic int lastIndexOf(int ch, int from)
ensure
( ((ch <= 0xffff && result == -1) IMPLIES for all i=0..from: charAt(i) != ch) && ((ch <= 0xffff && result != -1) IMPLIES ( (charAt(result) == ch) && for all i=0..from: charAt(i) != ch)) && ((ch > 0xffff && result == -1) IMPLIES for all codepoint indices i in 0..from: codePointAt(i) != ch) && ((ch > 0xffff && result != -1) IMPLIES ( (codePointAt(result) == ch) && for all i=0..from: codePointAt(i) != ch)
ch
- the character or code pointpublic int indexOf(String str)
NullPointerException
- if str is null.str
- the required substringpublic int indexOf(String str, int from)
ensure
(result != -1 IMPLIES startWith(str,result));
implemented in C for better performance.
NullPointerException
- if str is null.str
- the required substringfrom
- the index to start to search for the substring.public int lastIndexOf(String str)
ensure
(result != -1 IMPLIES startsWith(str,result) && result <= length());
NullPointerException
- if str is null.str
- the required substringpublic int lastIndexOf(String str, int from)
ensure
(result != -1 IMPLIES startsWith(str,result) && result <= from && result <= length());
NullPointerException
- if str is null.str
- the required substringfrom
- the starting index.public String substring(int from)
ensure
( (result.length() == length()-from) && (for all i=0..result.length(): result.charAt(i) == charAt(from+i)));
IndexOutOfBoundsException
- if from<0 or from>length().from
- the starting index.public String substring(int from, int end)
ensure
( (result.length() == end-from) && (for all i=0..result.length(): result.charAt(i) == charAt(from+i)));
IndexOutOfBoundsException
- if from<0 or end>length() or
endfrom
- the starting index (inclusive).end
- the end index (exclusive)..public CharSequence subSequence(int start, int end)
This implementation of the interface method CharSequence.subSequence behaves exactly as substring(start,end).
subSequence
in interface CharSequence
IndexOutOfBoundsException
- if start<0 || endstart
- the start position.end
- the end position.protected int indexOfCharSequence(CharSequence s, int from)
ensure
(result != -1 IMPLIES startsWith(s.toString(),result));
NullPointerException
- if s is null.s
- the required substringfrom
- the index to start to search for the substring.public String concat(String str)
For JamaicaVM, this returns this or str if str.length()==0 or this.length()==0, respectively.
ensure
( (result.length() == this.length()+str.length()) && (for all i=0..this.length(): result.charAt(i ) == charAt(i)) && (for all i=0..str .length(): result.charAt(length()+i) == str.charAt(i)))
NullPointerException
- if str is nullstr
- the other stringpublic String replace(char oldChar, char newChar)
ensure
( (result.length() == length()) && (for all i=0..length()-1: result.charAt(i) == (charAt(i)==oldChar ? newChar: charAt(i))))
oldChar
- the character to be replacednewChar
- the character oldChar is to be replaced withpublic boolean matches(String regex)
An invocation of this method of the form
str.matches(
regex)
yields exactly the
same result as the expression
Pattern
.matches(regex, str)
PatternSyntaxException
- if the regular expression's syntax is invalidregex
- the regular expression to which this string is to be matchedtrue
if, and only if, this string matches the
given regular expressionPattern
public boolean contains(CharSequence s)
s
- the sequence to search fors
, false otherwisepublic String replaceFirst(String regex, String replacement)
An invocation of this method of the form
str.replaceFirst(
regex,
repl)
yields exactly the same result as the expression
Pattern
.compile
(regex).matcher
(str).replaceFirst
(repl)
Note that backslashes (\
) and dollar signs ($
) in the
replacement string may cause the results to be different than if it were
being treated as a literal replacement string; see
Matcher.replaceFirst(java.lang.String)
.
Use Matcher.quoteReplacement(java.lang.String)
to suppress the special
meaning of these characters, if desired.
PatternSyntaxException
- if the regular expression's syntax is invalidregex
- the regular expression to which this string is to be matchedreplacement
- the string to be substituted for the first matchString
Pattern
public String replaceAll(String regex, String replacement)
An invocation of this method of the form
str.replaceAll(
regex,
repl)
yields exactly the same result as the expression
Pattern
.compile
(regex).matcher
(str).replaceAll
(repl)
Note that backslashes (\
) and dollar signs ($
) in the
replacement string may cause the results to be different than if it were
being treated as a literal replacement string; see
Matcher.replaceAll
.
Use Matcher.quoteReplacement(java.lang.String)
to suppress the special
meaning of these characters, if desired.
PatternSyntaxException
- if the regular expression's syntax is invalidregex
- the regular expression to which this string is to be matchedreplacement
- the string to be substituted for each matchString
Pattern
public String replace(CharSequence target, CharSequence replacement)
target
- The sequence of char values to be replacedreplacement
- The replacement sequence of char valuespublic String[] split(String regex, int limit)
The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.
When there is a positive-width match at the beginning of this string then an empty leading substring is included at the beginning of the resulting array. A zero-width match at the beginning however never produces such empty leading substring.
The limit
parameter controls the number of times the
pattern is applied and therefore affects the length of the resulting
array. If the limit n is greater than zero then the pattern
will be applied at most n - 1 times, the array's
length will be no greater than n, and the array's last entry
will contain all input beyond the last matched delimiter. If n
is non-positive then the pattern will be applied as many times as
possible and the array can have any length. If n is zero then
the pattern will be applied as many times as possible, the array can
have any length, and trailing empty strings will be discarded.
The string "boo:and:foo"
, for example, yields the
following results with these parameters:
Regex Limit Result : 2 { "boo", "and:foo" }
: 5 { "boo", "and", "foo" }
: -2 { "boo", "and", "foo" }
o 5 { "b", "", ":and:f", "", "" }
o -2 { "b", "", ":and:f", "", "" }
o 0 { "b", "", ":and:f" }
An invocation of this method of the form
str.split(
regex,
n)
yields the same result as the expression
Pattern
.compile
(regex).split
(str, n)
PatternSyntaxException
- if the regular expression's syntax is invalidregex
- the delimiting regular expressionlimit
- the result threshold, as described abovePattern
public String[] split(String regex)
This method works as if by invoking the two-argument split
method with the given expression and a limit
argument of zero. Trailing empty strings are therefore not included in
the resulting array.
The string "boo:and:foo"
, for example, yields the following
results with these expressions:
Regex Result : { "boo", "and", "foo" }
o { "b", "", ":and:f" }
PatternSyntaxException
- if the regular expression's syntax is invalidregex
- the delimiting regular expressionPattern
public static String join(CharSequence delimiter, CharSequence... elements)
CharSequence elements
joined together with a copy of
the specified delimiter
.
For example,Note that if an element is null, thenString message = String.join("-", "Java", "is", "cool"); // message returned is: "Java-is-cool"
"null"
is added.NullPointerException
- If delimiter
or elements
is null
delimiter
- the delimiter that separates each elementelements
- the elements to join together.String
that is composed of the elements
separated by the delimiter
StringJoiner
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
String
composed of copies of the
CharSequence elements
joined together with a copy of the
specified delimiter
.
For example,Note that if an individual element isList<String> strings = new LinkedList<>(); strings.add("Java");strings.add("is"); strings.add("cool"); String message = String.join(" ", strings); //message returned is: "Java is cool" Set<String> strings = new LinkedHashSet<>(); strings.add("Java"); strings.add("is"); strings.add("very"); strings.add("cool"); String message = String.join("-", strings); //message returned is: "Java-is-very-cool"
null
, then "null"
is added.NullPointerException
- If delimiter
or elements
is null
delimiter
- a sequence of characters that is used to separate each
of the elements
in the resulting String
elements
- an Iterable
that will have its elements
joined together.String
that is composed from the elements
argumentjoin(CharSequence,CharSequence...)
,
StringJoiner
public String toLowerCase(Locale locale)
String
to lower
case using the rules of the given Locale
. Case mapping is based
on the Unicode Standard version specified by the Character
class. Since case mappings are not always 1:1 char mappings, the resulting
String
may be a different length than the original String
.
Examples of lowercase mappings are in the following table:
Language Code of Locale | Upper Case | Lower Case | Description |
---|---|---|---|
tr (Turkish) | \u0130 | \u0069 | capital letter I with dot above -> small letter i |
tr (Turkish) | \u0049 | \u0131 | capital letter I -> small letter dotless i |
(all) | French Fries | french fries | lowercased all chars in String |
(all) | ![]() ![]() ![]() ![]() ![]() |
![]() ![]() ![]() ![]() ![]() |
lowercased all chars in String |
locale
- use the case transformation rules for this localeString
, converted to lowercase.toLowerCase()
,
toUpperCase()
,
toUpperCase(Locale)
public String toLowerCase()
This is equivalent to toLowerCase(Locale.getDefault()).
public String toUpperCase(Locale locale)
String
to upper
case using the rules of the given Locale
. Case mapping is based
on the Unicode Standard version specified by the Character
class. Since case mappings are not always 1:1 char mappings, the resulting
String
may be a different length than the original String
.
Examples of locale-sensitive and 1:M case mappings are in the following table.
Language Code of Locale | Lower Case | Upper Case | Description |
---|---|---|---|
tr (Turkish) | \u0069 | \u0130 | small letter i -> capital letter I with dot above |
tr (Turkish) | \u0131 | \u0049 | small letter dotless i -> capital letter I |
(all) | \u00df | \u0053 \u0053 | small letter sharp s -> two letters: SS |
(all) | Fahrvergnügen | FAHRVERGNÜGEN |
locale
- use the case transformation rules for this localeString
, converted to uppercase.toUpperCase()
,
toLowerCase()
,
toLowerCase(Locale)
public String toUpperCase()
This is equivalent to toUpperCase(Locale.getDefault()).
public String trim()
public String toString()
toString
in interface CharSequence
toString
in class Object
public char[] toCharArray()
ensure
( result.length == length() && (for all i=0..length()-1: result[i] == charAt(i)))
public static String valueOf(Object obj)
obj
- an object or nullpublic static String valueOf(char[] data)
ensure
( result.length() == data.length && for i in 0..data.length-1: result.charAt(i) == data[i])
NullPointerException
- if data is nulldata
- the character arraypublic static String copyValueOf(char[] data)
ensure
( result.length() == data.length && for i in 0..data.length-1: result.charAt(i) == data[i])
This is equivalent to valueOf(data)
NullPointerException
- if data is nulldata
- the character arraypublic static String valueOf(char[] data, int offset, int count)
ensure
( result.length() == count && for i in 0..count-1: result.charAt(i) == data[offset+i])
NullPointerException
- if data is null.IndexOutOfBoundsException
- if count<0 or offset<0 or
offset+count>data.length.data
- the character arrayoffset
- the index of the first character to use in the
stringcount
- the number of characters to use in the string.public static String copyValueOf(char[] data, int offset, int count)
ensure
( result.length() == count && for i in 0..count-1: result.charAt(i) == data[offset+i])
This is equivalent to valueOf(data,offset,count)
NullPointerException
- if data is null.IndexOutOfBoundsException
- if count<0 or offset<0 or
offset+count>data.length.data
- the character arrayoffset
- the index of the first character to use in the
stringcount
- the number of characters to use in the string.public static String valueOf(boolean b)
b
- the boolean valuepublic static String valueOf(char c)
A cache is used to avoid redundant allocations of the same string.
ensure
( result.length() == 1 && result.charAt(0) == c);
c
- the characterpublic static String valueOf(int i)
i
- an integerpublic static String valueOf(long l)
l
- a longpublic static String valueOf(float f)
f
- a floatpublic static String valueOf(double d)
d
- a doublepublic String intern()
s1.equals(s2) <==> s1.intern() == s2.intern()
Note that String constants (such as "Hello") are automatically interned by the virtual machine, such that the following holds:
s.equals("const string") <==> s.intern() == "const string"
intern() may be used for more efficient String equality comparison and to safe memory if many equal Strings are in use simulteneously.
However, intern() requires additional memory for each intern()ed String, such that this function should not be used without reason.
intern()ed Strings that become unused by the application will be reclaimed using weak references when the system memory runs low.
For JamaicaVM: intern() needs to allocate memory on the heap. If
this function is called from within RTSJ's scoped memory (ScopedMemory
), this method will anyway perform an
allocation on the heap for the resulting intern()ed String. The
resulting String will have its MemoryArea
set to ImmortalMemory
such that intern()ed
Strings can be used even by code that cannot access heap objects
(such as NoHeapRealtimeThread
). However,
the memory for intern()ed strings will be reclaimed after the
last reference to such a string is deleted.
public static String format(String format, Object... args)
The locale always used is the one returned by Locale.getDefault()
.
IllegalFormatException
- If a format string contains an illegal syntax, a format
specifier that is incompatible with the given arguments,
insufficient arguments given the format string, or other
illegal conditions. For specification of all possible
formatting errors, see the Details section of the
formatter class specification.NullPointerException
- If the format is nullformat
- A format stringargs
- Arguments referenced by the format specifiers in the format
string. If there are more arguments than format specifiers, the
extra arguments are ignored. The number of arguments is
variable and may be zero. The maximum number of arguments is
limited by the maximum dimension of a Java array as defined by
the Java
Virtual Machine Specification. The behaviour on a
null argument depends on the conversion.Formatter
public static String format(Locale l, String format, Object... args)
IllegalFormatException
- If a format string contains an illegal syntax, a format
specifier that is incompatible with the given arguments,
insufficient arguments given the format string, or other
illegal conditions. For specification of all possible
formatting errors, see the Details section of the
formatter class specificationNullPointerException
- If the format is nulll
- The locale to apply during
formatting. If l is null then no localization
is applied.format
- A format stringargs
- Arguments referenced by the format specifiers in the format
string. If there are more arguments than format specifiers, the
extra arguments are ignored. The number of arguments is
variable and may be zero. The maximum number of arguments is
limited by the maximum dimension of a Java array as defined by
the Java
Virtual Machine Specification. The behaviour on a
null argument depends on the conversion.Formatter
aicas GmbH, Karlsruhe, Germany —www.aicas.com
Copyright © 2001-2019 aicas GmbH. All Rights Reserved.