Program to Count no. of alphabets, digits and spaces present in a file

Posted in

Program to Count no. of alphabets, digits and spaces present in a file
vinaykhatri

Vinay Khatri
Last updated on March 29, 2024

    In this Programming tutorial, we will learn how to write a script in C++ and Python that can count the number of alphabets, digits, and spaces present in a text file. To write such a script we should know how to perform file handling in C++ and Python.

    With the help of file handling, we can read the data from a text file using the programming languages, and based on the data we can tell the number of alphabets, digits, and spaces present in the file.

    When we read data from a text file using file handling we generally read the data in string or character format. So in order to categorize whether the character or string is an alphabet or a digit we can use its ASCII value.

    Example

    The ASCII value of numbers starts from 48 to 57, which represents all numbers 0 to 9. For UpperCase Alphabets, the ASCII code starts from 41 up to 90. And for LowerCase alphabets the ASCII code starts from 97 up to 122.

    C Program to Count no. of alphabets, digits, and spaces present in a file

    #include <stdio.h>
    # include <string.h>
    
    int main()
    {
    	char ch;
    	int ascii,alpha_count=0,space_count=0,digit_count=0;
    	
     	// create a file pointer
    	FILE *file ;
     	
    	// open the file in read mode
            file = fopen("file1.txt", "r") ;
    
        while(1)
        {	//read the chracter from the file
        	ch = fgetc(file);
        	
    		
    	// if the chracter is in the end of the file    	
          	if ( ch == EOF )  
    		break ;
      		//print the read chracter
    		printf("%c", ch);		
            
            // convert the chracter into equivalent ascii code
            ascii=ch;
            
    	//check if the chracter is an Alphabet        
            if(ascii>63 && ascii<91 || ascii>96 && ascii<123)
                    alpha_count+=1; 
         
            // check if the chracter is an empty space 
            else if(ch==' ') 
                     space_count+=1; 
    
            //check if the chracter is a Digit 
            else if(ascii>47&&ascii<58)
                    digit_count++;
        }
        fclose(file);
    	printf("\n---------The Above File Statement Has----------------------\n");
        printf("No. of Alphabets :: %d \n",alpha_count);
        printf("No. Of Digits :: %d\n",digit_count);
        printf("No. Of White Spaces :: %d ",space_count);
        return 0;
    }

    Output

    G0QPLSZagX o1oB4OuAoaEGY JtmGiEtdEbBarKh0gX S1RXOi3oaMAKOx6Ct7WLl1om Q1yjf1Y2GLW g5RFs9kRgYgz2
    hg4 95HwAmpQgWsigOgibDS4qx7Jq ADqtEACDrZGG6aZ3ZDAt hb9QGR8V6qJE6NX mwx67PntAyLrcrDo vj2h ahFqR
    1cMphaOjRX ObkIu JzBgEORdvyhPR jUCc1uE LkqpZUBQ4 CudskxiV kn5qWy0 m4M51A qrNR2t 5Q8UVGQlo8HRor
    TRaL 7Nsu9rwRy2heHYBj rTgTAu9 PaMSUSOZqGzfGRfUwnW0UymRD32 1kSrMRULKbkbrKeCcRtiwW3F2pbMQF pNcd
    dY5y61m8NIB8mUWS Q3CKZMk94bZAmPcvoDTkMaxw4rCDc WDhjx06I4IotsxOWAs x25VIc4tKpbJf Lw2SY78nTdTM2
    9 ZRYoixdgef2vQ3 ncJcw5DYeYUIagHG0gNLWyylT gcEC3rgVmD6zVuPFJ0Oe0
    
    ---------The Above File Statement Has----------------------
    No. of Alphabets :: 421
    No. Of Digits :: 79
    No. Of White Spaces :: 32
    --------------------------------

    C++ Program to Count no. of alphabets, digits, and spaces present in a file

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main()
    {
        //open file in read mode
        ifstream file("file1.txt");
        char ch;
        int ascii,alpha_count=0,space_count=0,digit_count=0;
    
        while(file)
        {
            //read character
            file.get(ch);
            cout<<ch; 
            //convert the chracter into ASCII code
            ascii=ch; 
            // if the chracter is an Uppercase or LowerCase Alphabet
            if(ascii>63 && ascii<91 || ascii>96 && ascii<123) 
                    alpha_count++; 
           // if the chracter is an empty space
            else if(ch==' ') 
                    space_count++; 
           // if the chracter is a digit
            else if(ascii>47&&ascii<58)
                    digit_count++;
        }
        cout<<"The Above Data has";
        cout<<"\n"<<alpha_count<<" :: Alphabets\n";
        cout<<digit_count<<" ::  Digits\n";
        cout<<space_count<<" :: White Spaces";
    
        return 0;
    }

    Output

    G0QPLSZagX o1oB4OuAoaEGY JtmGiEtdEbBarKh0gX S1RXOi3oaMAKOx6Ct7WLl1om Q1yjf1Y2GLW g5RFs9kRgYgz2
    hg4 95HwAmpQgWsigOgibDS4qx7Jq ADqtEACDrZGG6aZ3ZDAt hb9QGR8V6qJE6NX mwx67PntAyLrcrDo vj2h ahFqR
    1cMphaOjRX ObkIu JzBgEORdvyhPR jUCc1uE LkqpZUBQ4 CudskxiV kn5qWy0 m4M51A qrNR2t 5Q8UVGQlo8HRor
    TRaL 7Nsu9rwRy2heHYBj rTgTAu9 PaMSUSOZqGzfGRfUwnW0UymRD32 1kSrMRULKbkbrKeCcRtiwW3F2pbMQF pNcd
    dY5y61m8NIB8mUWS Q3CKZMk94bZAmPcvoDTkMaxw4rCDc WDhjx06I4IotsxOWAs x25VIc4tKpbJf Lw2SY78nTdTM2
    9 ZRYoixdgef2vQ3 ncJcw5DYeYUIagHG0gNLWyylT gcEC3rgVmD6zVuPFJ0Oe0
    
    The Above Data has
    421 :: Alphabets
    79 ::  Digits
    32 :: White Spaces

    Python

    #open file in read mode
    with open("file1.txt", 'r') as file:
        #read file data
        data = file.read()
        #print file data
        print(data)
    
        alpha_count, space_count, digit_count= [0,0,0]
        
        #analyze file data
        for ch in data:
            #convert the chracter into ascii code
            ascii = ord(ch)
            if ascii>63 and ascii<91 or ascii> 96 and ascii<123:
                alpha_count+=1 
            elif ch ==" ":
                space_count+=1 
            elif ascii>47 and ascii<58:
                digit_count+=1
            
    print("The Above Data has")
    print(f"{alpha_count} :: Alphabets")
    print(f"{digit_count} :: Digits")
    print(f"{space_count} :: White Spaces")

    Output

    G0QPLSZagX o1oB4OuAoaEGY JtmGiEtdEbBarKh0gX S1RXOi3oaMAKOx6Ct7WLl1om Q1yjf1Y2GLW g5RFs9kRgYgz2
    hg4 95HwAmpQgWsigOgibDS4qx7Jq ADqtEACDrZGG6aZ3ZDAt hb9QGR8V6qJE6NX mwx67PntAyLrcrDo vj2h ahFqR
    1cMphaOjRX ObkIu JzBgEORdvyhPR jUCc1uE LkqpZUBQ4 CudskxiV kn5qWy0 m4M51A qrNR2t 5Q8UVGQlo8HRor
    TRaL 7Nsu9rwRy2heHYBj rTgTAu9 PaMSUSOZqGzfGRfUwnW0UymRD32 1kSrMRULKbkbrKeCcRtiwW3F2pbMQF pNcd
    dY5y61m8NIB8mUWS Q3CKZMk94bZAmPcvoDTkMaxw4rCDc WDhjx06I4IotsxOWAs x25VIc4tKpbJf Lw2SY78nTdTM2
    9 ZRYoixdgef2vQ3 ncJcw5DYeYUIagHG0gNLWyylT gcEC3rgVmD6zVuPFJ0Oe0
    
    The Above Data has
    421 :: Alphabets
    79 ::  Digits
    32 :: White Spaces

    Wrapping Up!

    In this programming tutorial, we learned how to use ASCII code values to count the number of alphabets, spaces, and digits present in a text file. We could also have used the inbuilt string methods provided by the programing language to check if the character is an alphabet or digit, but it's good to know how to analyze a character without using any inbuilt methods. Because in interviews you might have restricted to use of any inbuilt function.

    People are also reading:

    Leave a Comment on this Post

    0 Comments