Some useful String methods |
The demo program StringDemo
String courseName = "Data Structures"; int nameLength = courseName.length();
nameLength gets the value 15.
courseName.indexOf("S")
returns the value 5. Note that indexing starts at 0, as it does with arrays.
Of course, we can also say
String searchString = "S";
and then
courseName.indexOf(searchString)
Another option is:
public int indexOf(String s, int startIndex)
which begins its search at the specified index.
What's the result of
courseName.indexOf("Struct", 2) courseName.indexOf("Struct", 8) courseName.indexOf("s", 2) courseName.indexOf("s", 6)
Here is a method that searches for the number of occurrences of a string, word, in another string, text. document.
public int wordCount(String text, String word) { int count = 0; int pos = text.indexOf(word,0); while (pos >= 0) { count++; pos = text.indexOf(word,pos+word.length()); } return count; }
Recall from above that "s" and "S" are different strings.
Some useful String methods |