Quote:
Originally posted by Androto
Code:
void count_chars()
{
for(unsigned i=0; i<sSentence.size(); ++i)
for(unsigned j=0; j<CHARS; ++j)
if( sSentence.substr(i,1) == theAlphabet.substr(j,1) )
theAlphabetCount[j]++;
}
this is the last thing i don't get
|
Well this is the smart part basically. A loop in a loop.
Suppose you entered: Hi
Then this happens: sSentence.size() = 2
1) "H" is compared with all characters in the theAlphabet array.
theAlphabet array has 52 different characters in it, so "H" is compared with each of them. "H" is compared 52 times, for each character once.
2)"i" is compared with all characters in the theAlphabet array.
theAlphabet array has 52 different characters in it, so "H" is compared with each of them. "H" is compared 52 times, for each character once.
3) IF one if the characters in the sentence mathces a character in theAlphabet array, that index in theAlphabet array is raised with one.
4)
sSentence.substr(i,1)
We need only ONE character of the sentence so we use std::subtr();
std::substr() extracts a part of a string in a std::string!
The first parameter is the starting-index of the string (a std::string is an array too, but a luxury one) and the second parameter is how many characters we want to extract.
Examples:
string result;
string mystring = "Hello everybody";
result=mystring.substr(3,1); // result = "l"
result=mystring.substr(3,3); //result = "lo "
result=mystring.substr(0,3); //result = "Hel"
result=mystring.substr(6,4); //result = "ever"