R Program to Count Vowels and Consonants in a String

1. Introduction

Counting the number of vowels and consonants in a string is a fundamental text-processing task that can be useful in various contexts, from linguistics research to game development. In this guide, we will demonstrate how to count the vowels and consonants in a given string using the R programming language.

2. Program Overview

The program will:

1. Prompt the user to input a string.

2. Process the string to count the number of vowels and consonants.

3. Display the counts to the user.

3. Code Program

# Prompt the user for a string
cat("Enter the string to analyze: ")
input_string <- readLines(n=1)

# Convert the string to lowercase for uniformity
input_string <- tolower(input_string)

# Identify vowels using regular expression and count them
vowel_count <- sum(gregexpr("[aeiou]", input_string)[[1]] > 0)

# Identify consonants using regular expression and count them
consonant_count <- sum(gregexpr("[b-df-hj-np-tv-z]", input_string)[[1]] > 0)

# Display the count of vowels and consonants
cat("Number of vowels:", vowel_count, "\n")
cat("Number of consonants:", consonant_count, "\n")

Output:

Enter the string to analyze: HelloWorld
Number of vowels: 3
Number of consonants: 7

4. Step By Step Explanation

1. The program starts by prompting the user to input a string using the cat function. The string is then stored using the readLines function.

2. To ensure uniformity and simplify counting, the string is converted to lowercase using the tolower function.

3. Vowels are identified using a regular expression that matches any of the characters "aeiou". The gregexpr function is used for this purpose, and the resulting list is checked for positive values to count the number of matches, thereby giving us the number of vowels.

4. Consonants are similarly identified using a regular expression that matches any character in the set "b-df-hj-np-tv-z", representing all the consonants.

5. The program then displays the counts of vowels and consonants using the cat function.

Comments