Count and Print the alphabets having ASCII value not in the range [l, r] in C++


We are given with a string of any length and the task is to calculate the count and print the alphabets in a string having ASCII value not in the range [l,r]

ASCII value for character A-Z are given below

ABCDEFGHIJKLMNOPQRS
65666768697071727374757677787980818283


TUVWXYZ
84858687888990

ASCII value for characters a-z are given below

abcdefghijklmnopqrs
9
7
9
8
9
9
10
0
10
1
10
2
10
3
10
4
10
5
10
6
10
7
10
8
10
9
11
0
11
1
11
2
11
3
11
4
11
5


tuvwxyz
116117118119120121122

For Example

Input − String str = “point
      First = 111, Last = 117
Output − characters not in the given range are: i, n
      Count is: 2

Explanation − since i and n don't lies in the range of [111, 117] these characters will be counted.

Input − String str = “ABCZXY
      First = 65, Last = 70
Output − characters in the given range are: A, B, C
      Count is: 3

Explanation − since Z, X and Y don’t lie in the range of [65, 70] these characters will be counted.

Approach used in the below program is as follows

  • Input the string, start and end values to create the range and store it in variables let’s say, str.

  • Calculate the length of the string using the length() function that will return an integer value as per the number of letters in the string including the spaces.

  • Take a temporary variable that will store the count of characters and create a map let’s say, mp

  • Start the loop from i to 0 till i is less than the length of the string

  • Inside the loop, check if start is less than not equals to str[i] and str[i] is less than not equals to end

  • Inside the if, check if mp[str[i]] ! = 1 then print str[i] else increase mp[str[i]] by 1

  • Return the count

  • Print the result

Example

 Live Demo

#include <iostream>
#include <unordered_map>
using namespace std;
// To count the number of characters whose
// ascii value not in range [l, r]
int count_non_char(string str, int left, int right){
   int count = 0;
   // using map to print a character only once
   unordered_map<char, int> m;
   int len = str.length();
   for (int i = 0; i < len; i++) {
      if (!(left <= str[i] and str[i] <= right)){
         count++;
         if (m[str[i]] != 1){
            cout << str[i] << " ";
            m[str[i]]++;
         }
      }
   }
   // return the count
   return count;
}
// main code
int main(){
   string str = "tutorialspoint";
   int left = 102, right = 111;
   cout << "Characters and ";
   cout << "\nand count in the given range is: " << count_non_char(str, left, right);
   return 0;
}

Output

If we run the above code it will generate the following output −

Characters and
and count in the given range is: t u r a s p 8

Updated on: 15-May-2020

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements