C language---Write a function that takes as parameters a character, an integer,
ID: 3600146 • Letter: C
Question
C language---Write a function that takes as parameters a character, an integer, and a string and uses them as a pointer to check whether the character exists in the string or not. If not, it should return NULL. Otherwise, if the integer is 0, it should return a pointer to its first occurrence, otherwise to the last one. Write a C program that reads a string of less than 100 characters, a character, and an integer, calls the function, and displays the part of the string. For example, if the user enters "bootstrap", 't' and 0, the program should display tstrap. If it is "bootstrap", 't' and 3, the program should display trap.
Explanation / Answer
#include <stdio.h>
int main() {
int num,i=0,nsize,size=0,l=-1,k=0;
char ch,inp,st[100],temp[100];
printf("Enter the integer");
scanf("%d",&num);//input integer
printf("Enter the string");
while(1)
{
scanf("%c",&st[i]);//input string
if(st[i]==' ')
{
break;
}
++size;//calculate size of string
i++;
}
printf("Enter the character");
scanf("%c",&ch);//input character
if(num==0)
{
for(int j=0;j<size;j++)//check from start of string
{
if(st[j]==ch)//if character matches to string store position in l
{
l=j;
break;
}
}
nsize=size-l;//calculate size of new string
for(int p=0;p<size;p++)
{
temp[p]=st[l];//store the string from l position to end
l++;
}
}
else
{
for(int j=size-1;j>0;j--)//check from the end of string
{
if(st[j]==ch)//if character matches to string store position in l
{
l=j;
break;
}
}
nsize=size-l;//calculate size of new string
for(int p=0;p<size;p++)
{
temp[p]=st[l];//store the string from l position to end
l++;
}
}
printf("The result is");
for(int r=0;r<nsize;r++)
{
printf("%c",temp[r]);//print the result
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.