Tuesday, July 28, 2009

C++ programing question involving counting character occurrences.?

Given a "C" style string such as char[] s1 = "ka2d23UkLeA2" write a main function program that will count the number of occurrences of the character 'a' and 'A' and the number of occurrences of the character '2'.





The output for the sample string would be:





The number of As is 2.


The number of 2s is 3.

C++ programing question involving counting character occurrences.?
unsigned int aCount = 0;


unsignet int twoCounter = 0;





for(unsigned int i = 0; i %26lt; strlen(s1); ++i){


if(s1[i] == 'A' || s1[i] == 'a'){


aCount++;


} elseif (s1[i] == '2') {


twoCount++;


}


}


printf("The number of As is %d\n", aCount);


printf("The number of 2s is %d\n", twoCount);
Reply:Well, you already have two answers, I can verify that at least the first one is correct, however - if I may suggest a small change in it so that it won't loop over the string twice (strlen actually loop over the string to find the first zeroed char)





In that case - it would look like that:





int nAs = 0;


int n2s = 0;





for (int i=0; s1[i]; i++) // %26lt;%26lt; this is the changed line


{


if (s1[i] == 'a' || s1[i] == 'A')


nAs++;


else if (s1[i] == '2')


n2s++;


}


cout %26lt;%26lt; "# of As: " %26lt;%26lt; nAs %26lt;%26lt; endl;


cout %26lt;%26lt; "# of 2s: " %26lt;%26lt; n2s %26lt;%26lt; endl;
Reply:Well I'll give you the bulk. I think you can figure out the rest.





Loop through the string:





int nAs = 0;


int n2s = 0;





size_t len = strlen(s1);


for (int i=0; i %26lt; (int)len; i++)


if (s1[i] == 'a' || s1[i] == 'A')


nAs++;


else if (s1[i] == '2')


n2s++;





cout %26lt;%26lt; "# of As: " %26lt;%26lt; nAs %26lt;%26lt; endl;


cout %26lt;%26lt; "# of 2s: " %26lt;%26lt; n2s %26lt;%26lt; endl;


No comments:

Post a Comment