2016-08-23 113 views
0

我想根據用戶輸入發回一個列表作爲響應。我使用Spring MVC和我有不php stristr函數在java中相當於?

@RequestMapping(value = { "/hint" }, method = RequestMethod.GET,params={"word"}) 
public @ResponseBody String hint(ModelMap model,@RequestParam String word) { 
    System.out.println("Inside Hint"); 
    String[] hints = { "Ram", "Ra","R","Shyam" }; 

    String returnedhints=""; 
    // lookup all hints from array if $q is different from "" 
    if (word != null) { 
     System.out.println("i am here"); 
     //word = word.toLowerCase(); 
     int length = hints.length; 
     for (int j = 0; j < length; j++) { 
      System.out.println(word+"contains"+hints[j]+"="+word.contains(hints[j])); 
      if (hints[j].regionMatches(0,word, 0, hints[j].length())) { 
       returnedhints= returnedhints+","+hints[j]; 
      } 
     } 
    } 

return returnedhints; 

} 

在PHP服務器的代碼可以很容易地寫爲

if (stristr($q, substr($name, 0, $len))) { 
     if ($hint === "") { 
      $hint = $name; 
     } else { 
      $hint .= ", $name"; 
     } 

的處理,所以我想知道是否有任何等同於該控制器的方法在Java中的stristr函數?

P.S.用戶界面部分如下

function showHint(str) { 
    if (str.length == 0) { 
     document.getElementById("txtHint").innerHTML = ""; 
     return; 
    } else { 
     console.log(str); 

     var xmlhttp = new XMLHttpRequest(); 

     xmlhttp.onreadystatechange = function() { 

      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
       var list=xmlhttp.responseText.split(','); 
       console.log(list); 
       document.getElementById("txtHint").innerHTML = list; 
      } 
     }; 
     xmlhttp.open("GET", "/hint?word=" + str, true); 
     xmlhttp.send(); 
    } 
} 
<label>Name <input id="peak" type="text" name="peak_name" onkeyup="showHint(this.value)"> 
          <p id="peak"></p> 
         <p>Suggestions: <span id="txtHint"></span></p> 

回答

2

there的strstr的實施,適應它是不區分大小寫應該是可能的。

萬一鏈接頁面被刪除,這裏是代碼:

public class Solution { 
    public String strStr(String haystack, String needle) { 
     if(haystack==null || needle==null) return null; 
     int hLength=haystack.length(); 
     int nLength=needle.length(); 
     if(hLength<nLength) return null; 
     if(nLength==0) return haystack; 
     for(int i=0; i<=hLength-nLength; i++) 
     { 
     if(haystack.charAt(i)==needle.charAt(0)) 
     { 
      int j=0; 
      for(; j<nLength; j++) 
      { 
      if(haystack.charAt(i+j)!=needle.charAt(j)) 
      { 
       break; 
      } 
      } 
      if(j==nLength) return haystack.substring(i) ; 
     } 
     } 
     return null; 
    } 
}