String Method Problems
Check if a string contains the substring "is".
**Extract the last character from a string.
Check if a string starts with the character 'a'.
**Count the number of 'e's in a string.
Replace all instances of 'y' with 'z' in a string.
Get the index of the first space in a string.
Convert a string to all uppercase.
Check if a string is empty (length is 0).
Compare two strings ignoring case.
Split a string into an array at each comma.
** - The problem was to extract the last character from a string.
Strings in Java can be thought of as character arrays. We know that arrays are 0-indexed, meaning the first element is at index 0, second at 1 and so on.
To get the last character, we need the index of the last element in the array. Since arrays are 0-indexed, the index of the last element will always be length-1.
The string.length() method returns the total number of characters (length of the internal array). By subtracting 1 from it, we get the index of the last character.
For example, if the string is "Hello":
length() would return 5
length()-1 is 4
The character at index 4 is 'o'
So string.charAt(string.length()-1) lets us cleanly extract the last character without knowing the string length beforehand.
Last updated