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
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
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.
Comments
Lukas Dancak
Nov 11, 2:42 PMThis 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;
}
Learneroo
Nov 11, 2:52 PMHow does it handle words separated by one or more spaces?
Learneroo
Nov 11, 2:58 PMThis 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.
Bolke
Sep 28, 6:30 AMIt'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?
Bolke
Sep 28, 6:31 AMOk the [] were bad, because it's not an array, of course. But I'm still stumped.
Learneroo
Sep 29, 8:18 PMYour answer was very close but do you want to split the strings by commas or spaces?
Bolke
Sep 30, 5:50 AMLet's not go there, OK?
(Kidding. Of course. Thank you for the hint.)