161k views
0 votes
Assign searchResult with a pointer to any instance of searchChar in personName.

#include
#include
int main(void) {
char personName[100] = "Albert Johnson";
char searchChar = 'J';
char* searchResult = NULL;
/* Your solution goes here */
if (searchResult != NULL) {
printf("Character found.\\");
}
else {
printf("Character not found.\\");
}
return 0;
}

1 Answer

4 votes

Answer:

Here it the solution statement:

searchResult = strchr(personName, searchChar);

This statement uses strchr function which is used to find the occurrence of a character (searchChar) in a string (personName). The result is assigned to searchResult.

Headerfile cstring is included in order to use this method.

Explanation:

Here is the complete program

#include<iostream> //to use input output functions

#include <cstring> //to use strchr function

using namespace std; //to access objects like cin cout

int main() { // start of main() function body

char personName[100]; //char type array that holds person name

char searchChar; //stores character to be searched in personName

char* searchResult = nullptr; // pointer. This statement is same as searchResult = NULL

cin.getline(personName, 100); //reads the input string i.e. person name

cin >> searchChar; // reads the value of searchChar which is the character to be searched in personName

/* Your solution goes here */

searchResult = strchr(personName, searchChar); //find the first occurrence of a searchChar in personName

if (searchResult != nullptr) //if searchResult is not equal to nullptr

{cout << "Character found." << endl;} //displays character found

else //if searchResult is equal to null

{cout << "Character not found." << endl;} // displays Character not found

return 0;}

For example the user enters the following string as personName

Albert Johnson

and user enters the searchChar as:

J

Then the strchr() searches the first occurrence of J in AlbertJohnson.

The above program gives the following output:

Character found.

Assign searchResult with a pointer to any instance of searchChar in personName. #include-example-1
User Jensa
by
4.8k points