首页 > 解决方案 > 我想使用 Switch 语句在 Javascript 中查找元音出现

问题描述

我想编写一个带有 switch 语句的函数来计算一行文本中任何两个元音连续出现的次数。例如,在句子中

例如:

原始字符串 = “请阅读应用程序感谢我”。

字符串ea, ea, ui 中出现这种情况。

输出:3

function findOccurrences() {
    var str = "Pleases read this application and give me gratuity";
    var count = 0;

    switch (str) {
        case 'a':
            count++;
        case 'A':
            count++
        case 'e':
        case 'E':
        case 'i':
        case 'I':
        case 'o':
        case 'O':
        case 'u':
        case 'U':
            return 1;
        default:
            return 0;
    }
}

findOccurrences();

标签: javascripthtmlswitch-statement

解决方案


您可以使用正则表达式来查找出现次数。

原始字符串:Pl ea ses r ea d this application and give me grat ui ty

出现:eaeaioui

结果:4

正则表达式:

  • [aeiou]表示这些字符中的任何一个。
  • {2}正好 2 个({2,}如果您想连续匹配 2 个或更多字符,请更改为)
  • g在第一场比赛后不要停止(gi如果你想让它不区分大小写,请更改为)

function findOccurrences() {
  var str = "Pleases read this application and give me gratuity";
  var res = str.match(/[aeiou]{2}/g);
  return res ? res.length : 0;
}

var found = findOccurrences();

console.log(found);

编辑:与switch声明

function findOccurrences() {
  var str = "Pleases read this application and give me gratuity";
  var chars = str.toLowerCase().split("");
  var count = 0;
  
  // Loop over every character
  for(let i = 0; i < chars.length - 1; i++) {
    var char = chars[i];
    var next = chars[i + 1];
    
    // Increase count if both characters are any of the following: aeiou
    if(isCorrectCharacter(char) && isCorrectCharacter(next)) {
      count++
    }
  }
  
  return count;
}

// Check if a character is any of the following: aeiou
function isCorrectCharacter(char) {
  switch (char) {
    case 'a':
    case 'e':
    case 'i':
    case 'o':
    case 'u':
      return true;
    default:
      return false;
  }
}

var found = findOccurrences();

console.log(found);


推荐阅读