String Method Problems

  1. Check if a string contains the substring "is".

  2. **Extract the last character from a string.

  3. Check if a string starts with the character 'a'.

  4. **Count the number of 'e's in a string.

  5. Replace all instances of 'y' with 'z' in a string.

  6. Get the index of the first space in a string.

  7. Convert a string to all uppercase.

  8. Check if a string is empty (length is 0).

  9. Compare two strings ignoring case.

  10. 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.

Answers
  1. string.contains("is")

  2. string.charAt(string.length()-1)

  3. string.startsWith("a")

  4. string.split("e").length - 1

  5. string.replace("y", "z")

  6. string.indexOf(" ")

  7. string.toUpperCase()

  8. string.length() == 0

  9. string.equalsIgnoreCase(string2)

  10. string.split(",")

Last updated