如何在字符串中查找单词?

时间:2017-04-27 00:00:41

标签: javascript

挑战在于“找到沃尔多”。我正在试图弄清楚如何在函数/字符串中找到一个单词。“返回字符串'Waldo'开始的位置的索引。”

function findWaldo(str) {
    var waldoPosition;
    return waldoPosition
}

2 个答案:

答案 0 :(得分:0)

简单的任务:

function findWaldo(str) {
    return str.indexOf("waldo"); //the string you are looking for
}

很好地解释了here

答案 1 :(得分:0)

应该有一个可以轻松完成的库,比如string.indexOf,但您可以使用此算法手动执行此操作:

int count = 0;
string yourText = "This is waldo?";
string toSearch = "waldo";

for (int x = 0; x < yourText.Lenght; x++)
{
    if(yourText[x] == toSearch[0])
        if((count + 1) == toSearch.Lenght)
            return x;
    else
        count = 0;

   //here we'd say ehh there's not Waldo on the string
}
相关问题