Using suitable code, discuss the working of the following string functions:

6. B) Using suitable code, discuss the working of the following string functions:

  • i.strcat
  • ii.strcmp
  • iii.strcpy
  • iv.strlen
  • v.strstr

Answer:

i.strcat: 
It is used to concatenate i.e, combine the content of two strings.
Syntax: strcat(string 1, string 2); 
Example: char fname[30]={“bob”}; 
         char lname[]={“by”};
         printf(“%s”, strcat(fname,lname));
Output: bobby 
2.strcmp:
It is used to compare the contents of the two strings. 
Syntax: int strcmp(string 1, string 2); 
Example: char mystr_a[10] = “Hello”; 
         char mystr_b[10] = “Goodbye”; 
         –mystr_a == mystr_b; // NOT allowed! The correct way is if (strcmp(mystr_a, mystr_b )) 
         printf ("Strings are NOT the same."); 
         else 
         printf( "Strings are the same."); 
Here it will check the ASCII value of H and G i.e, 72 and 71 and return the diference 1.
3.strcpy:
It is possible to assign a value to a string variable using strcpy( ). It allows us to copy a string  from one location to another. The string to be copied can be  literal or string variable. The general form of call to strcpy is
strcpy(dest,source);
Strcpy()functionhastwoparameters.Thefirstisthedest,astringvariablewhosevalue  is going to be changed. The second is the source the string literal or variable which is going to be copied to thedestination.
Case1:Ex:charstr1[]="america";
         charstr2[]="india";
         strcpy(str1,str2);
         strcpy(america,india);
         america=7character
         india=5character
so first 5 character of america is replaced. 
Output is inidaca 

Case2:Ex:charstr1[10]=”india”
         charstr2[]="america";
         strcpy(str1,str2);
         strcpy(india,america);
         india=5character
         america=7character 
since 7 is greater than 5,all characters of india are replaced by america.
Output is america
4.strlen:It is used to return the length of a string.
Syntax: int strlen(string); 
Example:char fname[30]={“bob”}; 
        int length=strlen(fname); 
It will return 3.

Leave a Reply

Your email address will not be published. Required fields are marked *