// Purpose: Show how strchr() finds a character in a C-style string // Author: Dr Keith Shomper // Date: 9 Oct 2008 #include using namespace std; int main () { const int BUF_SIZE = 80; char *s, s1[BUF_SIZE]; char c; string s2; int pos; // Get a string cout << "Please enter a string: "; getline(cin, s2, '\n'); // Copy the standard string s2 into the character array s1 strcpy(s1, s2.c_str()); // Ask for a character to locate in s1 cout << "Please enter a character to locate: "; cin >> c; // Locate the first character represented by c in s1 s = strchr(s1, c); // Compute the position of character c if (s == NULL) { // In this case, the character we were looking for was not present cout << "There is no '" << c << "' in \"" << s1 << "\"\n"; } else { // s1 is the beginning of the string we are searching, s is were we need // to get to in that string. The position is the far s is from the // beginning of the string (and distances are found by subtraction) pos = s - s1; cout << "The position of the first '" << c << "' in \"" << s1 << "\" is " << pos << endl; } return 0; }