我正在尝试根据用户输入发回一个列表作为响应。我正在使用Spring mvc,我有这个处理器的控制器方法
@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。 UI部分如下
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>
答案 0 :(得分:2)
有一个strstr there的实现,应该可以使其适应不区分大小写。
如果删除了链接页面,请输入以下代码:
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;
}
}