Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substring search in Java

Tags:

java

string

I have a problem with string comparison. For example, there is this string:

"hello world i am from heaven"

I want to search if this string contains "world". I used following functions but they have some problems. I used String.indexof() but if I will try to search for "w" it will say it exists.

In short I think I am looking for exact comparison. Is there any good function in Java?

Also is there any function in Java that can calculate log base 2?

like image 431
user238384 Avatar asked Jan 01 '10 01:01

user238384


People also ask

How can I find a substring in string Java?

To locate a substring in a string, use the indexOf() method. Let's say the following is our string. String str = "testdemo"; Find a substring 'demo' in a string and get the index.

How do you find a substring in a string?

Run a loop from start to end and for every index in the given string check whether the sub-string can be formed from that index. This can be done by running a nested loop traversing the given string and in that loop running another loop checking for sub-strings starting from every index.

How can use substring in Java with example?

The substring begins with the character at the specified index and extends to the end of this string or up to endIndex – 1 if the second argument is given. Syntax : public String substring(int begIndex, int endIndex) Parameters : beginIndex : the begin index, inclusive. endIndex : the end index, exclusive.

How do you check if a string contains a word Java?

The Java String contains() method is used to check whether the specific set of characters are part of the given string or not. It returns a boolean value true if the specified characters are substring of a given string and returns false otherwise. It can be directly used inside the if statement.


1 Answers

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);
}
like image 183
cletus Avatar answered Oct 14 '22 22:10

cletus