You may notice that the function strchr in the <cstring> library searches for a character within a string, and returns the memory address (pointer) to where that character first occurs.
1.) Write your own version of the strchr function, int findchr( char text[ ], char target) , which returns the index of the first occurrance of the character target if it occurs within the string text. If target does not occur within the string, a -1 is to be returned.
2.) Write a main that tests your function by:
* declaring a char array
* prompting the user for a string and reading it into the array (thus creating a C string). The user string may contain blanks
* printing out the stored C-string
*prompting the user for a character to be searched for within the string
* call your function to determine if the character is in the string, and output a message to that effect
Code
#include<iostream>
using namespace std;
int findchr(char text[],char target)
{
int p=-1;
for(int i=0;i<strlen(text);i++)
{
if(text[i]==target)
return i;
}
return -1;
}
int main()
{
char s[100],t;
cout<<"Enter the string\n";
gets(s); //input the string
cout<<"Entered string is: "<<s;
cout<<"\nEnter the target character \n";
cin>>t; //input the target
int p=findchr(s,t);
cout<<"Index of the target is "<<p;
return 0;
}
Terminal Work
.
Get Answers For Free
Most questions answered within 1 hours.