I'm assuming the problems you're having with indexOf() related to you using the character version (otherwise why would you be searching for w when looking for world?). If so, indexOf() can take a string argument to search for:
String s = "hello world i am from heaven";
if (s.indexOf("world") != -1) {
// it contains world
}
as for log base 2, that's easy:
public static double log2(double d) {
return Math.log(d) / Math.log(2.0d);
}
Answer from cletus on Stack OverflowI'm assuming the problems you're having with indexOf() related to you using the character version (otherwise why would you be searching for w when looking for world?). If so, indexOf() can take a string argument to search for:
String s = "hello world i am from heaven";
if (s.indexOf("world") != -1) {
// it contains world
}
as for log base 2, that's easy:
public static double log2(double d) {
return Math.log(d) / Math.log(2.0d);
}
For an exact String comparison, you can simply do:
boolean match = stringA.equals(stringB);
If you want to check that a string contains a substring, you can do:
boolean contains = string.contains(substring);
For more String methods, see the javadocs
That is already in the String class:
String word = "cat";
String text = "The cat is on the table";
Boolean found;
found = text.contains(word);
Use the String.indexOf(String str) method.
From the JavaDoc:
Returns the index within this string of the first occurrence of the specified substring.
...
Returns: if the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned.
So:
boolean findInString(word, text)
{
return text.indexOf(word) > -1;
}