// MyStrchr - search a given character within // a string. Return the index of // of the result. #include #include // myStrchr - return the index of a test // character in a string. Return // a -1 if the character not found. int myStrchr(char target[], char testChar) { // loop through the character string; // stop if we hit the end of the string int index = 0; while(target[index]) { // if the current member of the // string matches the target // character... if (target[index] == testChar) { // ...then exit break; } // skip to the next character index++; } // if we ended up at the end of the // string without encountering the // character... if (target[index] == '\0') { // ...return a -1 rather than // the length of the array index = -1; } // return the index calculated return index; } // test the myStrchr function with different // string combinations void testFn(char szString[], char cTestChar) { cout << "The offset of " << cTestChar << " in " << szString << " is " << myStrchr(szString, cTestChar) << "\n"; } int main(int nArgs, char* pszArgs[]) { testFn("abcdefg", 'c'); testFn("abcdefg", 'a'); testFn("abcdefg", 'g'); testFn("abcdefc", 'c'); testFn("abcdefg", 'x'); return 0; }