String Manipulation
| English | Chinese | Pinyin |
|---|---|---|
| immutable | 不可变 | bù kě biàn |
Strings and indexing
- A
Stringis a sequence of characters, numbered from0. - In
"HELLO", index0is'H', index1is'E', … index4is'O'. s.length()gives the count of characters; the last index islength() - 1.- Off-by-one errors here are the most common String bug.
substring
s.substring(start, end)returns the characters from indexstartup to but not includingend."HELLO".substring(1, 3)→"EL"(indices1and2, not3).s.substring(start)(one argument) goes fromstartto the end.- The result's length is
end - start.
indexOf and equals
s.indexOf("lo")returns the first index where the text appears, or-1if not found.s.equals(t)tests whether two Strings have the same characters — returns aboolean.- Use
.equals(), never==, to compare String contents. ==compares references (addresses), not the characters.
Strings are immutable
- A String is immutable 不可变: its characters can never be changed once created.
- Methods like
substringandtoUpperCasereturn a new String — they don't edit the original. s.toUpperCase();alone does nothing visible; you must store the result:s = s.toUpperCase();- Immutability is why String methods always hand back a fresh value.
Compare String contents with .equals(), never ==. == tests whether two references point to the same object, not whether the characters match — so a == b can be false even when both are "cat". And Strings are immutable: s.toUpperCase() returns a new String and leaves s unchanged unless you reassign s = s.toUpperCase();.
Working with "HELLO":
"HELLO".length()→5; index0is'H', index4is'O'."HELLO".substring(1, 4)→"ELL"(indices1, 2, 3)."HELLO".indexOf("L")→2(firstL);.equals("hello")→false(case differs).
A String is indexed from 0 (last index length()-1). substring(start, end) returns indices start to end-1; indexOf finds a position (or -1). Compare contents with .equals(), not ==. Strings are immutable — methods return a new String, so reassign to keep the change.
Indexing HELLO from 0
substring(1, 4) takes indices 1, 2, 3 → ELL.
In the String "HELLO", which character is at index 0?
Strings are indexed from 0, so index 0 is 'H'.
What does "HELLO".substring(1, 3) return?
Indices 1 and 2 (up to but not including 3) → EL.
To compare whether two Strings have the same characters, you should use...
.equals() compares contents; == compares references.
s.toUpperCase(); on its own changes the String s in place.
Strings are immutable — you must reassign s = s.toUpperCase();.
What does "HELLO".indexOf("L") return (the first L)?
The first 'L' is at index 2.