我想使用 Switch 语句在 Javascript 中查找元音出现 [英] I want to find vowel occurences in Javascript using Switch statement

查看:38
本文介绍了我想使用 Switch 语句在 Javascript 中查找元音出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用switch语句写一个函数来统计一行文本中任意两个元音连续出现的次数.例如,在句子中

I want to write a function with a switch statement to count the number of occurrences of any two vowels in succession in a line of text. For example, in the sentence

例如:

Original string = Pleases read 这个应用程序并给我 gratuity".

Original string = "Pleases read this application and give me gratuity".

在字符串 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();

推荐答案

如果你坚持使用 switch,你还需要一个循环和一个标志来标记你是否已经看到了元音.

If you insist on using switch you'd also need a loop and a flag to mark if you have seen a vowel already.

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

  for (const letter of str.toLowerCase()) {
    switch (letter) {
      case 'a':
      case 'e':
      case 'i':
      case 'o':
      case 'u':
        {
          if (haveSeenVowel) {
            count++;
            haveSeenVowel = false;
          } else {
            haveSeenVowel = true;
          }
          break;
        }
      default:
        haveSeenVowel = false
    }
  }

  return count
}

console.log(findOccurrences());

这篇关于我想使用 Switch 语句在 Javascript 中查找元音出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆