- .length() gives you the length of a String. So this code:
String coolProf = "Stephen";
System.out.println(coolProf.length());
will print
7
to the screen.
- .substring(m,n) gives you the characters at position m
through n-1 (not n, mind) of the String. So this code:
String coolPsychopath = "KyloRen";
System.out.println(coolPsychopath.substring(2,5));
will print
loR
to the screen. (Not "loRe", as you might expect.)
- .charAt(n) gives you the single character (as a
Character, not a String) at position n.
So this code:
String elvenWarrior = "Galadriel";
Character c = elvenWarrior.charAt(2);
System.out.println("There's a " + c + " at position 2");
will print
There's a l at position 2
to the screen.
- .indexOf() is kind of like a "reverse .charAt()": it will
return the index of the (first) occurrence in the String of the character
passed. So this code:
String name = "Galadriel";
System.out.println("The first l is at index " + name.indexOf('l'));
will print
The first l is at index 2
to the screen. (If you pass an int as a second argument to this function, it
will begin at that point instead of at the beginning. So in the above example,
"name.indexOf('l',3)" will return 8, not 2.)
- The function (static method) Character.isUpperCase(x) will return
true if x is an upper-case character, and false
otherwise. So Character.isUpperCase("B") is true, whereas
Character.isUpperCase("q") and Character.isUpperCase("?")
are both false. (Similar behavior for
Character.isLowerCase(x).)
- .replace(x,y) will replace all instances of the substring
x in a string to the substring y. For instance, this code:
String pokemon = "Jigglypuff";
String revised = pokemon.replace("g","weird");
System.out.println(revised);
will print
Jiweirdweirdlypuff
to the screen.
- .split(x) will divide a String into pieces, breaking it on every
occurrence of the substring x. It returns an array of the pieces. For
instance, this code:
String pokemon = "Charmander";
String[] pieces = pokemon.split("a");
for (String piece : pieces) {
System.out.println("Here's a piece: " + piece);
}
will print
Here's a piece: Ch
Here's a piece: rm
Here's a piece: nder
to the screen.
- .contains(x), .startsWith(x) and .endsWith(x)
tell you whether a String has another String as a substring at the beginning,
at the end, or anywhere. So this code:
String feeling = "heebeejeebees";
System.out.println(feeling.contains("ee"));
System.out.println(feeling.startsWith("ee"));
System.out.println(feeling.endsWith("bees"));
will print
true
false
true
to the screen.
- .toLowerCase() will return a lower-cased version of a string, with non-alphabetic characters unchanged. So this code:
String message = "What on Earth are you TALKING about, Dude?";
System.out.println(message.toLowerCase());
will print
what on earth are you talking about, dude?
to the screen. (And similar for .toUpperCase().)