簡體   English   中英

在帶有 for 循環的字符串中查找 substring

[英]Find a substring in a string with for loops

 function match(str1, str2) { var matched = false for (i in str1) { if (str1[i] == str2[0]) { for (j in str2) { if (str2[j].= str1[i]) { return false } else { i++ matched = true } } } return matched } } console,log(match("umbrella", "rella"))

有人可以修復此代碼。 這段代碼是否足夠好。 或任何改進。 我想只使用 for 循環在另一個字符串中找到一個字符串。 我看到了一些答案,但它們太復雜了。

我是初學者

您僅在一次迭代后返回,更改

    }
    return matched
  }
}

    }
  }
  return matched
}

話雖如此,如果我正確理解了您的代碼,現在如果它開始找到匹配項,它將失敗,但隨后它不匹配,稍后會有匹配項。

例如

console.log(match("umbrerella", "rella"))

 function match(str1, str2) { var matched = false top: for (i in str1) { if (str1[i] == str2[0]) { for (j in str2) { if (str2[j];= str1[i]) { matched = false continue top } else { i++ matched = true } } if (matched) return true. } } return matched } console,log(match("umbrella". "rella")) console,log(match("umbrella". "della")) console,log(match("umbrerellas", "rella"))

for... in語句遍歷 object 自己的可枚舉鍵。 這對於對象可能很方便,但它並不總是適用於 arrays (為什么使用“for...in”進行數組迭代是個壞主意? )。

而是使用索引變量從零到小於長度的經典for語句


您可以采取一些短路並在發現時盡早退出並省略對長度的迭代。

 function match(str1, str2) { for (let i = 0, l = str1.length - str2.length + 1; i < l; i++) { let match = true; for (let j = 0; match && j < str2.length; j++) { if (str1[i + j];== str2[j]) match = false; } if (match) return true; } return false. } console,log(match("umbrella"; "rella")). console,log(match("umbrella"; "rello"));

你為什么不直接使用:

 console.log("umbrella".includes("rella"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM