简体   繁体   English

在 Javascript 中不带 includes/indexOf/Regex 的字符串中查找 substring

[英]Find substring in string without includes/indexOf/Regex in Javascript

I'd like to figure out if a substring is within a string without using the Javascript built in methods of includes , indexOf , (any similar to those), or regular expressions.我想弄清楚 substring 是否在字符串中,而不使用 Javascript 的内置方法includesindexOf ,(任何类似的)或正则表达式。 Basically just looking to learn an algorithm approach.基本上只是想学习一种算法方法。

This is what I have so far这是我到目前为止所拥有的

function isSubstring(string, substring){
    substringIndex = 0;

    // loop through string
    for(let i = 0; i< string.length; i++){

       //check the current substring index if it matches 
       if(string[i] === substring[substringIndex]){
           substringIndex++
          //continue searching... Would i then have to call another function recursively?
       }

    }

}

I'm having trouble understanding how to build the algorithm.我无法理解如何构建算法。 Once it finds that first character that matches, I would just go to the next one and if it matches continue to the next index of the string?一旦找到匹配的第一个字符,我将 go 到下一个,如果它匹配继续到字符串的下一个索引? Would I then need a recursive function that is separate from the looping I am currently doing?然后我需要一个与我当前正在做的循环分开的递归 function 吗? I'm trying to get better at algorithmic thinking.我正在努力提高算法思维。 Thanks.谢谢。

Many approaches are possible. 许多方法都是可能的。 Here is one: Create a simpler function which will check if a first string is at concrete specified position, let's call it start , in a second string. 这是一个:创建一个更简单的函数,该函数将检查first字符串是否在特定的指定位置,让我们在second字符串中将其称为start It is quite simple: You compare first[i] with second[start+i] for all i in range 0 to length of first - 1. 非常简单:对于范围为0到first -1的所有i ,您将first[i]second[start+i]进行比较。

Then the second step will be to repeat this function for all start positions from 0 to length of second string, while checking the boundaries (you cannot read after end of a string). 然后,第二步将是在从0到第二个字符串的长度的所有起始位置重复此功能,同时检查边界(在字符串结束后无法读取)。

You can also do some optimizations later, when the first version will work. 当第一个版本可用时,您也可以稍后进行一些优化。 :-) :-)

Here is an optimized example of the algorythm isSubstring. 这是算法算法isSubstring的优化示例。 It iterates only through the minimum number of characters required. 它仅迭代所需的最少字符数。

For example, if the string is 20 characters long and the substring is only 5 characters long, when we get to the 16th position of the string we can assume that the substring doesn't exist within the string (16 + 5 = 21 > 20) 例如,如果字符串的长度为20个字符,而子字符串的长度仅为5个字符,则当到达字符串的第16位时,我们可以假定子字符串在字符串中不存在(16 + 5 = 21> 20 )

 function isSubstring(str, sub){ if(sub.length > str.length) return false; for(let i = 0; i < str.length - sub.length + 1; i++){ if(str[i] !== sub[0]) continue; let exists = true; for(let j = 1; j < sub.length && exists; j++){ if(str[i+j] === sub[j]) continue; exists = false; } if(exists) return true; } return false; } //expected true console.log(isSubstring("hello world", "hello")); console.log(isSubstring("hello world", "world")); console.log(isSubstring("hello world", "d")); console.log(isSubstring("hello world", "ow")); console.log(isSubstring("hello world", "rl")); console.log(isSubstring("hello world", "")); //expected false console.log(isSubstring("hello world", "hello world 1")); console.log(isSubstring("hello world", "helloo")); 

On each iteration over the length of the haystack, use slice to extract the characters from that index to (the index plus the length of the needle). 在干草堆length上的每次迭代中,使用slice来从该索引中提取字符(索引加针的长度)。 If the sliced string matches the needle, return true: 如果切片的字符串与针匹配,则返回true:

 function isSubstring(string, substring) { for (let i = 0; i < string.length; i++) { const sliced = string.slice(i, i + substring.length); if (sliced === substring) { return true; } } return false; } console.log(isSubstring('foobar', 'oob')); console.log(isSubstring('foobar', 'baz')); 

Since you expressed interest in a recursive method, here's something to consider. 由于您对递归方法表达了兴趣,因此需要考虑一些事项。 Clicking on the yellow markdown parts reveal the spoilers. 单击黄色的降价部分会显示扰流板。

function f(str, sub, i=0, j=0){
  if (j && j == sub.length)

return true;

  if (i == str.length)

return false;

  if (str[i] == sub[j])
    return f(str, sub,

i+1, j+1);

  return f(str, sub,

i+1, 0);

}
    function isSubstring(str, sub) {
        return str.split(sub).length > 1
    }

No includes, no .indexOf, no RegExp. 不包括,不包含.indexOf,不包含RegExp。 Just strings. 只是字符串。

using only one loop pseudo code:只使用一个循环伪代码:

 const containSubstr = (str, substr) => { let count = 0; let i = 0; let startIndex = 0; while (i < str.length) { if (substr[count] === str[i]) { if (count === substr.length - 1) { return true; } count++; } else { count = 0; i = startIndex; startIndex++; } i++; } return false; }; console.log(containSubstr("ababad", "abad"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM