How to define a function with two arguments – string and character that returns the index of second occurrence of that character in the string or -1 if there are less than two occurrences.
Well, write a function that has a string argument 'str' and a char argument 'ch'. Then use either a count variable and a for loop, or string::find (twice) to find the index.
#include <iostream>
#include <string>
usingnamespace std;
short function (char* MyString, char MyChar, short num) {
short times = 0, i, lastINDEX = 0, lenght = strlen (MyString) + 1; //declare local variables and initilize required
for (i = 0; i < lenght; i++) {
if (MyString [i] == MyChar) {
lastINDEX = i; //record index of last character seen
++times; //record how many times MyChar has benn seen
continue; // other if statements are irelevant if true, so skip them and speed up :)
}
if (times == num)
return i; // return index of MyChar if character is founded so many times as requested
if (i == lenght - 1) {
cout << num << ".Character '" << MyChar << "' not found but index of last character found is ";
return lastINDEX; // num-th character not foud so return last character
}
}
return lastINDEX; //this return is here only because of compiler warning (it's usleles)
}
int main () {
char test [] = "here is damn strng to check out the where misterious char s is";
cout << function (test, 's', 2) << endl;
/* 1.arg = enter string where to search
2.arg = enter char which to search
3.arg = how many times to search for that character */
system ("pause");
return 0;
}