Substring

Remember what the arguments mean

s.substring(start, end)

start is the index of the first character of the substring

end is the exclusive end, i.e. the index of character after the last character of the substring.

Note that end can be s.length() even though that is not a legal index.

One argument version

s.substring(start)

This is equivalent to s.substring(start, s.length())

I.e. the substring starting at start and going to the end of the string.

String s = "food";

» s.substring(0, 3)
"foo"

» s.substring(1)
"ood"

» s.substring(1, 3)
"oo"

A useful identity

(s.substring(0, x) + s.substring(x)).equals(s)

Because x is exclusive when it is the second argument (in the first call) and inclusive as the first argument (in the second call) the two substrings add up to the original string.

Another one

s.substring(start, end).length() == end - start;

Getting one-character out of a string

s.substring(i, i + 1)

Alternatively:

s.substring(i - 1, i)

Chopping something out of a string

int pos = s.indexOf(other);
s = s.substring(0, pos) + s.substring(pos + other.length())

The first substring gets everything up to, but not including, the first character of other.

The second substring starts after the occurrence of other and goes to the end of s.

Also please note!

indexOf and substring are different!

indexOf takes a String and returns an int.

substring takes ints and returns a String

Too many students use indexOf when they mean substring.