Question:10
C program to take input for a string , further take input for a character to search , check and print whether the character is present in the string or not, if present also print how many times it is present?(Search and count)
Sol:
/* Using for loop */ #include<stdio.h> int main() { char n[20],ch; int i=0,z=0; printf("Enter any string "); gets(n); printf("Enter the character to search "); scanf("%c",&ch); for(i=0;n[i]!='\0';i++) { if(n[i]==ch) { z=z+1; } } if(z==0) printf("character is not present"); else printf("character is present %d times",z); return(0); }
/* Using while loop */ #include<stdio.h> int main() { char n[20],ch; int i=0,z=0; printf("Enter any string "); gets(n); printf("Enter the character to search "); scanf("%c",&ch); while(n[i]!='\0') { if(n[i]==ch) { z=z+1; } i++; } if(z==0) printf("character is not present"); else printf("character is present %d times",z); return(0); }
/* Output */ case:1 Enter any string hello Enter the character to search l character is present 2 times case:2 Enter any string hello Enter the character to search k character is not present
Question:11
C program to take input for a string , further take input for a character to search and input for a character to replace with?(Search and replace)
Example:
n=”hello”
character to search : l
character to replace with : a
output: heaao
Sol:
/* Using for loop */ #include<stdio.h> int main() { char n[20],ch,ch1; int i=0,z=0; printf("Enter any string "); gets(n); printf("Enter the character to search "); fflush(stdin); scanf("%c",&ch); printf("Enter new character "); fflush(stdin); scanf("%c",&ch1); for(i=0;n[i]!='\0';i++) { if(n[i]==ch) { z=1; n[i]=ch1; } } if(z==0) printf("character is not present"); else printf("After replacement string is %s",n); return(0); }
/* Using while loop */ #include<stdio.h> int main() { char n[20],ch,ch1; int i=0,z=0; printf("Enter any string "); gets(n); printf("Enter the character to search "); fflush(stdin); scanf("%c",&ch); printf("Enter new character "); fflush(stdin); scanf("%c",&ch1); while(n[i]!='\0') { if(n[i]==ch) { z=1; n[i]=ch1; } i++; } if(z==0) printf("character is not present"); else printf("After replacement string is %s",n); return(0); }
/* Output */ case:1 Enter any string hello Enter the character to search k Enter new character l character is not present case:2 Enter any string hello Enter the character to search l Enter new character a After replacement string is heaao
Question:12
C program to take input for a string and copy it into another string ?
example:
n1=”hello”
copied string n2=”hello”
Sol:
#include<stdio.h> int main() { char n1[20],n2[20]; int i=0,j=0; printf("Enter any string "); gets(n1); while(n1[i]!='\0') //for(;n1[i]!='\0';) { n2[i]=n1[i]; i++; } n2[i]='\0'; printf("copied string is %s\n",n2); getch(); return(0); }
/* Output */ Enter any string computer copied string is computer