Skip to content

Java String API

Java ArrayList —— List 接口的可变数组实现。

1 class · 12 methods

ArrayList<E>

12 methods

List 接口的可变数组实现。允许 null 和所有元素。

int length()

将指定元素追加到列表末尾。

Returns

int

Example

java
"hello".length()   // 5
"".length()         // 0
char charAt(int index)

返回指定位置处的元素。抛出 IndexOutOfBoundsException。

Parameters

NameTypeDescription
indexint从 0 开始的索引。

Returns

char

Example

java
"hello".charAt(1)  // 'e'
"hello".charAt(0)  // 'h'
String substring(int beginIndex, int endIndex)

替换指定位置处的元素。返回之前的元素。

Parameters

NameTypeDescription
indexint从 0 开始的索引。
elementint新元素。

Returns

String

Example

java
"hello".substring(1, 3)  // "el"
"hello".substring(2)      // "llo"
int indexOf(String str)

移除指定位置处的元素。返回被移除的元素。

Parameters

NameTypeDescription
indexString从 0 开始的索引。

Returns

int

Example

java
"hello".indexOf("ll")  // 2
"hello".indexOf("z")    // -1
String[] split(String regex)

返回列表中的元素数量。

Parameters

NameTypeDescription
regexStringDelimiting regex.

Returns

String[]

Example

java
"a,b,c".split(",")        // ["a", "b", "c"]
"hello".split("")         // ["h","e","l","l","o"]
"a-b--c".split("-")       // ["a", "b", "", "c"]
String trim()

如果列表不包含任何元素则返回 true。

Returns

String

Example

java
"  hi  ".trim()  // "hi"
"\n hello\n".trim()  // "hello"
String replace(CharSequence target, CharSequence replacement)

如果列表包含指定元素则返回 true(使用 equals)。

Parameters

NameTypeDescription
targetCharSequence要查找的元素。
replacementCharSequenceReplacement.

Returns

String

Example

java
"a-b-c".replace("-", "_")   // "a_b_c"
"hello".replace("l", "L")   // "heLLo"
boolean equals(Object anObject)

返回 o 首次出现的索引,未找到则返回 -1。

Parameters

NameTypeDescription
anObjectObject要查找的元素。

Returns

boolean

Example

java
"hello".equals("hello")  // true
"hello".equals("Hello")  // false (case-sensitive)
new String("x") == "x"   // false (reference compare)
new String("x").equals("x")  // true
int compareTo(String anotherString)

移除列表中的所有元素。

Parameters

NameTypeDescription
anotherStringStringString to compare.

Returns

int

Example

java
"abc".compareTo("abd")   // negative
"abc".compareTo("abc")   // 0
"abd".compareTo("abc")   // positive
String toUpperCase()

返回一个数组,按正确顺序包含列表中的所有元素。

Returns

String

Example

java
"hello".toUpperCase()  // "HELLO"
"café".toUpperCase()    // "CAFÉ"
String toLowerCase()

Convert all characters to lower case using the default locale.

Returns

String

Example

java
"HELLO".toLowerCase()  // "hello"
"CAFÉ".toLowerCase()    // "café"
boolean contains(CharSequence s)

Return true if and only if this string contains the specified sequence of char values.

Parameters

NameTypeDescription
sCharSequenceSequence to search for.

Returns

boolean

Example

java
"hello world".contains("world")  // true
"hello".contains("z")             // false