"Check out some other things you can do with substrings:"
8) How do I find a substring?
The indexOf and lastIndexOf methods let you search for strings within strings. There are 4 versions of these methods:
The indexOf method looks for a string in a specified String. The method can search for the string from the beginning of the specified String, or starting from some index (the second method). If the string is found, then the method returns the index of its first character; if it is not found, then it returns -1.
Method(s) | Example(s) |
---|---|
|
|
Result:
|
|
|
|
Result:
|
"The lastIndexOf method searches for the specified string backwards from the end of our String! This method can search for a string from the very end of our String, or starting from some index (the second method). If the string is found, then the method returns the index of its first character; if it is not found, then it returns -1."
Method(s) | Example(s) |
---|---|
|
|
Result:
|
|
|
|
Result:
|
9) How do I replace part of a String with another String?
"There are three methods for this."
The replace method replaces all occurrences of a particular character with another character.
The replaceAll method replaces all occurrences of a substring with another string.
The replaceFirst method replaces the first occurrence of a passed substring with a specified string.
Method(s) | Example(s) |
---|---|
|
|
Result:
|
|
|
|
Result:
|
|
|
|
Result:
|
"But you need to be careful with these. In the last two methods (replaceAll and replaceFirst), the string we are looking for is passed as a regular expression, not a simple string. But I'll talk about that later."
GO TO FULL VERSION