![]() |
We are going to implement an algorithm by which we can count the number of alphabets present in a given string. A string can consist of numbers, special characters, or alphabets. Examples: Input: Str = "adjfjh23" In this article, we are going to implement it with two different approaches. Table of Content Approach 1: Using RegExpIn this approach, we will use Regular Expression to count the number of alphabets in a string. A regular expression is a sequence of characters that forms a search pattern. The a-zA-Z pattern finds any character between the brackets a to z and A to Z. Syntax: /pattern/modifiers; Example:
Output 13 Approach 2: Using for LoopIn this approach, we will use for loop to traverse each character of a string, and use str.charAt() method to check the character value between ‘A’ to ‘Z’. Syntax: for (statement 1 ; statement 2 ; statement 3){ Example:
Output 13 Approach 3: Using String.prototype.split() and Array.prototype.filter()This approach splits the string into an array of characters using `split()`, then filters out non-alphabetic characters using `filter()` with a regular expression, and returns the length of the filtered array. Example:
Output 10 Approach 4: Using Array.prototype.reduce()In this approach, we convert the string into an array of characters using split(”) and then use the reduce() method to count how many of these characters are alphabets. The reduce() method will iterate through each character and maintain a count of those that match the alphabet pattern [a-zA-Z]. Example:
Output 10 Approach 5: Using Array.prototype.every()In this approach, we first split the string into an array of characters using split(). We then use a for loop to iterate through each character, using the every() method to check if the character is an alphabet. We maintain a count of how many characters are alphabets. Example:
Output 10 Approach 6: Using Array.prototype.map() and Array.prototype.reduce()In this approach, we will first split the string into an array of characters using split(”). We then map each character to 1 if it is an alphabet (using a regular expression) or 0 otherwise. Finally, we use the reduce() method to sum up the values, giving us the count of alphabetic characters. Example:
Output 10 |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |