Java中的子字符串搜索

use*_*384 6 java string

我有字符串比较的问题.例如,有这个字符串:

"hello world i am from heaven"
Run Code Online (Sandbox Code Playgroud)

我想搜索这个字符串是否包含"world".我使用了以下功能,但它们有一些问题.我曾经使用String.indexof()但如果我试图搜索"w"它会说它存在.

总之,我认为我正在寻找确切的比较.Java中有什么好的功能吗?

还有Java中的任何函数可以计算日志库2吗?

cle*_*tus 25

我假设indexOf()您使用角色版本时遇到的问题(否则为什么在寻找世界时会搜索w?).如果是这样,indexOf()可以使用字符串参数来搜索:

String s = "hello world i am from heaven";
if (s.indexOf("world") != -1) {
  // it contains world
}
Run Code Online (Sandbox Code Playgroud)

对于log base 2,这很容易:

public static double log2(double d) {
  return Math.log(d) / Math.log(2.0d);
}
Run Code Online (Sandbox Code Playgroud)

  • 对不起,我真的不明白你要做什么.你可以解释吗? (4认同)

Ric*_*d H 9

要进行精确的字符串比较,您只需执行以下操作:

boolean match = stringA.equals(stringB);
Run Code Online (Sandbox Code Playgroud)

如果要检查字符串是否包含子字符串,可以执行以下操作:

boolean contains = string.contains(substring);
Run Code Online (Sandbox Code Playgroud)

有关更多String方法,请参阅javadoc