char sum in string

I need help finding the sum of char elements in a string. For example the string below is "test string" and I want to sum the number of times "t" and "s" occur in the string which should be 5. I think i'm having trouble on the sum portion. So far I have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{   string testString = "test string";
    char letter1 = 't';
    char letter2 = 's';
    int sum = 0;
    //int length = testString.length();
    for(int i = 0; i < testString.length(); i++){
        if(testString[i]==letter1 and testString[i]==letter2){
            //sum = testString[letter1] + testString[letter2];
            //sum++;
            sum = testString.find(letter1) + testString.find(letter2);
        }
    }cout<<sum<<endl;
    return 0;
}
Below is a way (not the way) of what I would do:

I would create a counter to count the letters 't' and 's'. Then inside the for loop, I would use the if statement to find the specific letter and count it (if found). Then, out side of the for loop, I would add the two counters.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int countLetter1 {0}; // Initialized on C++ 11 style
int countLetter2 {0}; // Initialized on C++ 11 style

for (int = 0; i < testString.length(); i++)
{
      if (testString[i] == letter1)
         countLetter1++;

      else if (testString[i] == letter2)
         countLetter2++;
}

sum = countLetter1 + countLetter2;

cout << sum << endl;
Last edited on
Topic archived. No new replies allowed.