R Program to Count the Number of Vowels in a String

In this article, we will discuss how to Count the Number of Vowels in a String with its working example in the R Programming Language. It is a fundamental in programming that allows us to repeatedly execute a block of code as long as a specified condition remains true. It’s often used for tasks like iterating over elements in a data structure, such as printing the elements of a vector. Vowels are the letters ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’. We have to count no. of vowels in a string where a sample string is given.

Prerequisites:

You should have the following in place before using the R programme to count the number of vowels in a string:

  • Make sure that R or RStudio is installed on your PC. R and RStudio can be downloaded and installed from their respective official websites, respectively (https://www.r-project.org/ and https://rstudio.com/).
  • Basic knowledge of R: Get to know the fundamental elements of R programming, including variables, functions, loops, and conditional statements. You can efficiently understand and change the code with the aid of this understanding.

Methodology:

  • Iteratively going through each character of the string to determine whether it is a vowel is the standard methodology for counting the number of vowels in a string. A detailed description of the process is provided below:
  • Initialise Variables: Create a variable to hold the input string, then initialise a second variable to 0 to keep track of the vowel count.
  • Repeat the String Iteratively: Utilise a loop to iterate through the input string’s characters, such as a for loop.
  • Examine the vowels: Verify whether each character inside the loop is a vowel. Vowels are commonly “a,” “e,” “i,” “o,” and “u,” and you can accomplish this check using conditional expressions (for example, if-else).
  • Increment Count: Increase the vowel count variable if the character is a vowel.
  • Repeat: Once you have tested every character in the string, repeat this procedure for each subsequent character.
  • Depending on your particular use case, you can either display or return the final vowel count from the function after the loop.
  • This method allows you to use R to precisely count the number of vowels in a given string.

Syntax:

countVowels <- function(input_string) {
vowels <- c("a", "e", "i", "o", "u")
count <- 0

for (char in strsplit(input_string, "")[[1]]) {
if (char %in% vowels) {
count <- count + 1
}
}

return(count)
}

Example 1:

R

countVowels <- function(input_string) {
  vowels <- c("a", "e", "i", "o", "u")
  count <- 0
  
  for (char in strsplit(input_string, "")[[1]]) {
    if (char %in% vowels) {
      count <- count + 1
    }
  }
  
  return(count)
}

input_string <- "Hello Beginner"
result <- countVowels(input_string)
print(paste("Number of vowels:", result))

Contact Us