Hi guys,
This exercise goes as follows:
- Write a function that counts the number of occurences of a pair of letters in a string and another that does the same in a zero-terminated array of char(a C-style string). For example, the pair "ab" appears twice in "xabaacbaxabb".
Now, I found the following solution to the C-style version:
#include <iostream>
void compareChar(char *myArr, char *mySecArr);
int main()
{
char mychar[] = "xabaacbaxabb";
char letters[2];
compareChar(mychar, letters);
std::cin.ignore(2);
return 0;
}
void compareChar(char *myArr, char *mySecArr)
{
int count = 0;
std::cout << "Enter two letters to be compaired with the char string 'xabaacbaxabb'" << std::endl;
std::cin >> mySecArr;
while(strlen(mySecArr) != 2)
{
std::cout << "Wrong amount of letters, try again!" << std::endl;
std::cin >> mySecArr;
}
for (int i = 0; myArr[i] != 0; i++)
{
if((myArr[i] == mySecArr[0]) && (myArr[i+1] == mySecArr[1]))
count++;
}
std::cout << "The pair '" << mySecArr << "' appears " << count << " time(s) in " << myArr << "." << std::endl;
}
I was wondering if any of you could tell me how I can improve this, the reason for asking is that at the end of the last comparison if((myArr[i] == mySecArr[0]) && (myArr[i+1] == mySecArr[1]))
the myArr[i+1]
goes out of bound. Isn't that bad coding?