Java中的子字符串搜索

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

"hello world i am from heaven" 

我想搜索这个字符串是否包含“world”。 我使用了以下function,但它们有一些问题。 我使用了String.indexof()但是如果我尝试搜索“w”,它会说它存在。

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

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

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

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

对于log base 2,这很容易:

 public static double log2(double d) { return Math.log(d) / Math.log(2.0d); } 

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

 boolean match = stringA.equals(stringB); 

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

 boolean contains = string.contains(substring); 

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

嗨我的版本如下:

 package com.example.basic; public class FindSubString { public String findTheSubString(String searchString, String inputString){ StringBuilder builder = new StringBuilder(inputString); System.out.println("The capacity of the String " + builder.capacity()); System.out.println("pos of" + builder.indexOf(searchString)); return builder.substring(builder.indexOf(searchString),builder.indexOf(searchString)+searchString.length()); } public static void main(String[] args) { String myString = "Please find if I am in this String and will I be found"; String searchString = "I am in this String"; FindSubString subString = new FindSubString(); boolean isPresent = myString.contains(searchString); if(isPresent){ System.out.println("The substring is present " + isPresent + myString.length()); System.out.println(subString.findTheSubString(searchString,myString)); } else { System.out.println("The substring is ! present " + isPresent); } } } 

如果它有用,请告诉我。

我终于得到了解决方案。

 public void onTextChanged(CharSequence s, int start, int before, int count) { ArrayList> arrayTemplist = new ArrayList>(); String searchString = mEditText.getText().toString(); if(searchString.equals("")){new DownloadJSON().execute();} else{ for (int i = 0; i < arraylist.size(); i++) { String currentString = arraylist.get(i).get(MainActivity.COUNTRY); if (searchString.toLowerCase().contains(currentString.toLowerCase())) { //pass the character-sequence instead of currentstring arrayTemplist.add(arraylist.get(i)); } } } adapter = new ListViewAdapter(MainActivity.this, arrayTemplist); listview.setAdapter(adapter); } }); } 

用以下代码替换上面的代码:

 public void onTextChanged(CharSequence s, int start, int before, int count) { ArrayList> arrayTemplist = new ArrayList>(); String searchString = mEditText.getText().toString(); if(searchString.equals("")){new DownloadJSON().execute();} else{ for (int i = 0; i < arraylist.size(); i++) { String currentString = arraylist.get(i).get(MainActivity.COUNTRY); if (currentString.toLowerCase().contains(searchString.toLowerCase())) { //pass the character-sequence instead of currentstring arrayTemplist.add(arraylist.get(i)); } } } adapter = new ListViewAdapter(MainActivity.this, arrayTemplist); listview.setAdapter(adapter); } });