javascript:查找字符串中重复(相邻和不相邻)的字符
javascript: Find repeated (adjacent & non-adjacent) chars in a string
我试图在字符串中找到重复的字符并使其正常工作,但是当我输入相邻的字符时出现问题。我的函数最终输出第一个连续重复的字符。知道为什么我的第一个条件没有执行吗?预期输出应该是 "C",但我最终得到 "B"
function findFirstRepeatedChar(s){
for(let i=0; i<s.length; i++){
if(s[i] == s[i+1]){
return s[i];
}else if(s.indexOf(s[i], i+1) != -1){
return s[i];
}
}
return false;
}
console.log(findFirstRepeatedChar("ABCCBD"));
//console.log(findFirstRepeatedChar("ABCDB"));
//console.log(findFirstRepeatedChar("ABCDE"));
在您的代码中,您将 return 放入 for 中,然后您只得到一个值。
如果你创建一个数组并将重复的元素放入其中,之后你可以显示元素数组。
尝试此代码并获取 BC 字符串 (ABCCBD) B(ABCDB) 和无 (ABCDE)
<!DOCTYPE html>
<html>
<head>
<script>
function findFirstRepeatedChar(s){
var arr=[];
for(let i=0; i<s.length-1; i++){
if(s[i] == s[i+1] && (i+1<=s.length)){
//return s[i];
arr.push(s[i]);
}else if(s.indexOf(s[i], i+1) != -1 && (i+1<=s.length)){
//return s[i];
arr.push(s[i]);
}
}
for(i=0; i<arr.length; i++){
console.log(arr[i]);
}
return false;
}
console.log(findFirstRepeatedChar("ABCCBD"));
//console.log(findFirstRepeatedChar("ABCDB"));
//console.log(findFirstRepeatedChar("ABCDE"));
</script>
</head>
<body>
</body>
</html>
希望对您有所帮助
您 return 是第一个顺序匹配结果而不是第一个相邻匹配结果。存储非相邻匹配项并在函数末尾 return 将它们移动到 return 第一个相邻匹配项。
function findFirstRepeatedChar(s){
var ot = false;
for(let i=0; i<s.length; i++){
if(s[i] == s[i+1]) {
return s[i];
} else if(s.indexOf(s[i], i+1) != -1){
ot = s[i];
}
}
return ot;
}
console.log(findFirstRepeatedChar("ABCCBD"));
我试图在字符串中找到重复的字符并使其正常工作,但是当我输入相邻的字符时出现问题。我的函数最终输出第一个连续重复的字符。知道为什么我的第一个条件没有执行吗?预期输出应该是 "C",但我最终得到 "B"
function findFirstRepeatedChar(s){
for(let i=0; i<s.length; i++){
if(s[i] == s[i+1]){
return s[i];
}else if(s.indexOf(s[i], i+1) != -1){
return s[i];
}
}
return false;
}
console.log(findFirstRepeatedChar("ABCCBD"));
//console.log(findFirstRepeatedChar("ABCDB"));
//console.log(findFirstRepeatedChar("ABCDE"));
在您的代码中,您将 return 放入 for 中,然后您只得到一个值。 如果你创建一个数组并将重复的元素放入其中,之后你可以显示元素数组。
尝试此代码并获取 BC 字符串 (ABCCBD) B(ABCDB) 和无 (ABCDE)
<!DOCTYPE html>
<html>
<head>
<script>
function findFirstRepeatedChar(s){
var arr=[];
for(let i=0; i<s.length-1; i++){
if(s[i] == s[i+1] && (i+1<=s.length)){
//return s[i];
arr.push(s[i]);
}else if(s.indexOf(s[i], i+1) != -1 && (i+1<=s.length)){
//return s[i];
arr.push(s[i]);
}
}
for(i=0; i<arr.length; i++){
console.log(arr[i]);
}
return false;
}
console.log(findFirstRepeatedChar("ABCCBD"));
//console.log(findFirstRepeatedChar("ABCDB"));
//console.log(findFirstRepeatedChar("ABCDE"));
</script>
</head>
<body>
</body>
</html>
希望对您有所帮助
您 return 是第一个顺序匹配结果而不是第一个相邻匹配结果。存储非相邻匹配项并在函数末尾 return 将它们移动到 return 第一个相邻匹配项。
function findFirstRepeatedChar(s){
var ot = false;
for(let i=0; i<s.length; i++){
if(s[i] == s[i+1]) {
return s[i];
} else if(s.indexOf(s[i], i+1) != -1){
ot = s[i];
}
}
return ot;
}
console.log(findFirstRepeatedChar("ABCCBD"));