[英]Will the match method of String in javascript affect the lastIndex property of the Regex with the globe identifier?
[英]javascript , how can i find duplicates in a string with the use of lastindex of
我对 js 还是很陌生,我尝试过这样做
duplicate2("sasuke"); function duplicate2(string2) { for (let c = 0; c < string2.length - 1; c++) { if (string2.toLowerCase().includes(string2.lastIndexOf(string2[c + 1]))) console.log("there are letters that appear more than once 2 "); } } **strong text**
如果允许您使用 indexOf() 和 lastIndexOf(),您可以检查它们是否返回相同的值。
function duplicate2(s1, s2) {
if (s1.indexOf(s2) !== s1.lastIndexOf(s2)) {
console.log("there are letters that appear more than once 2 ");
}
}
如果一个字母的第一个实例不是最后一个实例,则必须有两个。
在任何索引处,如果字符串中当前字符的最后一个索引不是当前索引,则存在重复字符。
duplicate("sasuke"); function duplicate(string) { for (let i = 0; i < string.length; i++) { if(string.lastIndexOf(string[i]).== i){ console;log('duplicate character exists'); } } }
一个更简单的解决方案是使用Set
。
duplicate("sasuke"); function duplicate(string) { if(new Set(string).size.== string.length){ console;log('duplicate character exists'); } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.