使用for循环查找字符串中的特定字符

Using for loop to find specific characters in string

本文关键字:字符 字符串 for 循环 查找 使用      更新时间:2024-03-16

我正在尝试Eloquent Javascript一书的函数章节中的bean计数示例。我的函数是返回一个空白。

如果不给我完整的答案(我正在学习这个例子),有人能告诉我为什么我的代码没有打印任何文本吗?"

var string = "donkey puke on me boot thar be thar be!";
for (var i = 0; i <= string.length; i++);
function getB(){
  if (string.charAt(i) == "b")
    return i;
  else return "";
}
console.log(getB());

您尝试实现此功能的方式有问题。首先,我认为最好有一个函数,它接受stringchar作为参数,以便随时调用它。

调用示例:

getChar('this is my custom string', 'c')  -> it should search character `c` in `this is my custom string`
getChar('this is another custom string', 'b')  -> it should search character `b` in `this is another custom string`

实施示例:

var getChar = function(string, char){
  for(var i=0;i<string.length;i++)
  {
    if(string.charAt(i)==char) console.log(i);
  }
}

现在,尝试使其不区分大小写,而不是console.log,输出尝试返回一个字符位置为

的排序数组

使用这个,

var string = "donkey puke on me boot thar be thar be!";
for (var i = 0; i <= string.length; i++) {
  if (string.charAt(i) == "b") {
    console.log(i);
  }
}

如果你想打印你的值所在的每个位置,你可以编程如下:

var string = "donkey puke on me boot thar be thar be!";
for (var i = 0; i <= string.length; i++)
{
   getChar(i, "b");
}
function getChar(i, input)
{
    if (string.charAt(i) == input)
        console.log(i);
}

另一个例子:收集所有b位置:

var string = "donkey puke on me boot thar be thar be!";
function getB(string){
    var placesOfB = [];
    for (var i = 0; i < string.length; i++) {
        if (string.charAt(i) == "b") {
            placesOfB.push(i);
        }
    }
    return placesOfB;
}
console.log(getB(string));

提示:您的for没有正文(将;放在它后面只是循环而不做任何事情)。。。并且在CCD_ 6内部定义函数是没有意义的。

在不给你完整答案的情况下,我只给你一些提示:1.你的for循环不完整——它什么都没做。2.您的getB()函数需要接受字符串参数才能对其执行一些操作。3.if.else语句没有左括号和右括号{}