How to count letters of alphabet in a string?

Hello, creating a program where I count all the letters of the alphabet from a user submitted string.

How would I go about this?

I am completely new, so simplicity is best. I am suppose to use arrays.
Last edited on
If i understand it, you should create a function which counts a single letter. Iterate through the string: there are also build in functions for that. I show how to implement it.
for(auto letter : string) if you are using C++11. Then compare the letter to the argument. If they are equal, increase the return value.

1
2
3
4
5
6
7
8
9
10
11
unsigned int countChar(char letter, const std::string& str)
{
    unsigned int ret = 0;

    for(auto ltr : str)
    {
        if(ltr == letter){ ret++; };
    };

    return ret;
};


you can substitute the second parameter with a const char*, and use a for loop with strlen(str):

1
2
3
4
5
6
7
8
9
10
11
unsigned int countChar(char letter, const char* str)
{
    unsigned int ret = 0;

    for(unsigned int i=0; i < strlen(str); i++)
    {
        if(str[i]== letter){ ret++; };
    };

    return ret;
};


You can use tolower or toupper to count lower and uppercase letters too. Create an array of numbers (sized 26), then use the function:

1
2
3
4
5
6
7
unsigned int numbers[26];
memset(numbers, 0, 26);

for(int i = 0; i < 26; i++)
{
    numbers[i] = countChar(i+'a', userstring);
};
Last edited on
Not using c++11. just the regular one. those codes aren't working
That first example you provided im guessing is going to be something along the lines of what i need. However, i don't know c++11 and theres a few things in those lines of code that are throwing me off.
I hope the following code helps. :) I have used Turbo C++ 4.5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream.h>
int main()
{ char str[100];
  int i,count=0;
  cout << "Enter the string: ";
  cin.getline(str,100);

  for(i=0;str[i]!='\0';i++)
  {if(str[i]!=' '&&str[i]!='.')
	count++;
	}

	cout << "\nThe number of alphabets in string are: " << count;

	return 0;
	}
Last edited on
Topic archived. No new replies allowed.