AP Computer Science A · Unit 1 lecture · Part 10 of 11 · 12 min

1.15 String manipulationStrings: text you can slice

Mr. Thompkins
Strings are on every AP exam, in multiple choice and on the free response. Good news: you only need a handful of methods, and every one of them comes down to counting positions carefully. Get your pencil.

A String is an object that holds a sequence of characters. String is a class in java.lang, but it gets special treatment: a String literal like "rain" creates a String object for you, without new. (You can also write new String("rain"), and the Quick Reference lists that constructor.)

Strings are immutable: once a String object is made, its characters can never change. Every String method that seems to change a String actually builds and returns a new one. So s.substring(1) leaves s exactly as it was. If you want s to change, you have to assign the result back: s = s.substring(1);.

?Wait, how did + work with Strings again?
When either side of + is a String, + concatenates: it glues the two together, turning a number into text first. "Lap " + 3 is "Lap 3". It goes left to right, so 1 + 2 + "x" is "3x" but "x" + 1 + 2 is "x12". s += "!" is short for s = s + "!".
String s"rain"old String, unchanged"rainbow"brand-new Strings = s + "bow"; moves the arrow
Concatenation builds a new String. The old one is untouched, and s now points to the new one.

Indexes

Each character in a String has a position number called an index, and indexes start at 0. In "basketball", b is at index 0 and the last l is at index 9. The length is 10, so the last index is always length() - 1. Using an index outside 0 to length() - 1 throws a StringIndexOutOfBoundsException, a kind of IndexOutOfBoundsException.

index0123456789
sbasketball
substring(3, 6)ket
substring(6)ball
Write the indexes under the letters before you do anything else. substring(3, 6) takes indexes 3, 4 and 5.
?Wait, why is the last index length() - 1 and not length()?
Because counting starts at 0. A String with 3 characters uses indexes 0, 1 and 2: three positions, and the last one is 2. In general the indexes run from 0 to length() - 1, so length() itself is one step past the end.

The methods on the Quick Reference

length() returns the number of characters. substring(from, to) returns the characters from index from up to, but not including, index to, so its length is to - from. substring(from) returns everything from index from to the end. To get the single character at index k, as a String, use substring(k, k + 1). indexOf(str) returns the index where str first appears, or -1 if it doesn't appear at all.

substring is forgiving at exactly one spot: an index equal to length() is allowed, as long as you don't go past it. "basketball".substring(10) is the empty String "", and substring(0, 10) is the whole word. substring(11), or a from bigger than to, throws an exception.

1String s = "basketball";2System.out.println(s.length());13System.out.println(s.substring(6));24System.out.println(s.substring(3, 6));25System.out.println(s.indexOf("ball"));36System.out.println(s.indexOf("a"));37System.out.println(s.indexOf("Ball"));48System.out.println(s.substring(s.length() - 1));5
  1. line 2 10 characters, so indexes 0 to 9
  2. line 3-4 Start index included, end index not
  3. line 5-6 Where the first match starts
  4. line 7 Not found (B is not b): -1
  5. line 8 The last character, as a String
output › 10 ball ket 6 1 -1 l
The slicing and searching methods on "basketball", run under Java 17.
Pause and think
What does "basketball".substring(4, 4) return? What about "basketball".substring(9, 10)?
I thought about it. Show me
substring(4, 4) is the empty String "": it starts at 4 and stops before 4, so it takes nothing (length 4 - 4 = 0). substring(9, 10) is "l", the last character, one character long.

Comparing Strings

equals(other) returns true when two Strings contain exactly the same characters in the same order. It's case-sensitive, so "maple".equals("Maple") is false. compareTo(other) compares alphabetically, character by character, and returns an int: negative if this String comes first, positive if it comes after, and 0 if they're equal. Only the sign matters on the exam.

compareTo looks at the first position where the two Strings differ. If one String is a prefix of the other, the shorter one comes first: "man" comes before "mango". And it compares character codes, where every capital letter comes before every lowercase letter, so "Zebra" comes before "apple". Never use == to compare String contents. It checks whether two references point to the same object, which is a different question (more on that in Unit 2).

1String a = "maple";2String b = "mango";3System.out.println(a.equals("Maple"));14System.out.println(a.compareTo(b) > 0);25System.out.println(b.compareTo("man") > 0);36System.out.println("Zebra".compareTo("apple") < 0);47System.out.println(a.compareTo("maple"));5
  1. line 3 equals is case-sensitive
  2. line 4 First difference: p comes after n
  3. line 5 A prefix comes first, so mango is after man
  4. line 6 Every capital letter comes before every lowercase one
  5. line 7 Same characters: exactly 0
output › false true true true 0
equals and compareTo, run under Java 17. Check each true and false against the rules above.
Rearrange a name
A String full holds a name written last name first, like "Lopez, Maria": the last name, a comma, one space, then the first name. Write statements that build a String named flipped holding "Maria Lopez". Your code must work for any name in that form.
  1. Find the comma: int comma = full.indexOf(",");. For "Lopez, Maria", comma is 5.
    Why?
    Never hard-code 5. The question says "any name," and indexOf finds the position for each one.
  2. The last name is everything before the comma: String last = full.substring(0, comma);. That's indexes 0 to 4: "Lopez".
    Why?
    substring stops before the end index, which is exactly what you want: the comma itself is left out.
  3. The first name starts two characters after the comma (skip the comma and the space): String first = full.substring(comma + 2);. That's "Maria".
  4. Glue them with a space: String flipped = first + " " + last;. That's "Maria Lopez".

Answer:

int comma = full.indexOf(",");
String last = full.substring(0, comma);
String first = full.substring(comma + 2);
String flipped = first + " " + last;

Stuck? Get a hint
  1. Which method tells you where the comma is?
  2. The last name ends right before the comma. substring's end index is not included.
  3. The first name starts after the comma and the space: comma + 2.
Check yourself
What is printed?
String w = "racecar";
String t = w.substring(w.indexOf("e"));
System.out.println(t + w.indexOf("car"));
  1. Aecar4
  2. Becar3
  3. Ccecar4
  4. Dcar4
Show the answer

A. r0 a1 c2 e3 c4 a5 r6. indexOf("e") is 3, so substring(3) is "ecar". indexOf("car") finds the first "car", which starts at 4. A String plus an int concatenates: "ecar4". Choice B mixes up the two searches: 3 is where "e" is, but "car" starts at 4.

Check yourself
Which expression is true?
  1. A"apple".compareTo("Apple") < 0
  2. B"cat".compareTo("catalog") < 0
  3. C"dog".equals("Dog")
  4. D"pear".compareTo("peach") < 0
Show the answer

B. "cat" is a prefix of "catalog", so it comes first and compareTo is negative. In A, lowercase a comes after capital A, so the result is positive. C is false because equals is case-sensitive. In D, the first difference is r versus c, and r comes after c, so the result is positive.

Exam tip from Mr. T

Before you touch any String question, write the word and number its letters from 0. Then for every substring call, write the start and the end and say out loud "up to, not including." It takes ten seconds and it is the difference between the right answer and the trap.

  • Strings are immutable. Methods return new Strings; assign the result if you want to keep it.
  • Indexes run from 0 to length() - 1. Going outside throws StringIndexOutOfBoundsException.
  • substring(a, b): from a up to, not including, b (length b - a). substring(a): from a to the end. substring(k, k + 1): one character.
  • indexOf returns the first match's index, or -1.
  • equals compares characters exactly (case counts). compareTo: negative, 0 or positive. Never == for contents.