More String Methods

Premium Content - Free Preview

Below are 3 additional String methods. After reviewing them, you should be able to solve the challenges and tasks below and the challenges in String Programming Practice.

indexOf(c) - Finds the character 'c' within the String and returns the index where 'c' first occurs. For example:

 int value = "abcaz".indexOf('a'); 

value will equal 0, the index of the first 'a' in the String. This method can also be used to get the indexOf a substring:

value = "abcaz".indexOf("az");

This will set value to 3 since "az" starts at index 3.

replace(oldChar, newChar) - Returns a new string resulting from replacing all occurrences of oldChar with newChar. For example:

String verb = "food".replace('o', 'e');

verb will equal "feed". This method can also be used to replace Strings instead of characters:

End of Free Content Preview. Please Sign in or Sign up to buy premium content.


  • This is my code for third BONUS task. But it did not pass test. What is wrong ?

    public int wordCount()
    String[] words = content.split(" ");
    int i = words.length;
    return i;

  • How does it handle words separated by one or more spaces?

  • This bonus task could be solved in different ways, but the simplest (though not covered) would be to split the text on a regex pattern for one or more white spaces.

  • It's a pity you can't get the answer somewhere on the site.

    I try
    String[] snacks = words.replace('x' , 'c').split(",");

    and it is not correct, but how would I ever find out what I'm doing wrong?

  • Ok the [] were bad, because it's not an array, of course. But I'm still stumped.

  • Your answer was very close but do you want to split the strings by commas or spaces?

  • Let's not go there, OK?

    (Kidding. Of course. Thank you for the hint.)

Contact Us
Sign in or email us at [email protected]