Problem Solving Through C (BCA) 1st Sem Previous Year Solved Question Paper 2022

Practice Mode:
13.

Discuss the following string handling functions with the help of example code :

(i) strcat()
(ii) strcmp()
(iii) strcpy()

Explanation

string functions are strcat(), strcmp(), and strcpy().

  1. strcat() (String Concatenation):

  • The strcat() function is used to concatenate (append) one string to the end of another. It is used to combine two strings into one.

#include <stdio.h>

#include <string.h>



int main() {

char destination[20] = "Hello, ";

char source[] = "World!";

strcat(destination, source); // Concatenate source to the end of destination

printf("Concatenated string: %s\n", destination);

return 0;

}

Output:

Concatenated string: Hello, World!



  1. strcmp() (String Comparison):

  • The strcmp() function is used to compare two strings. It returns 0 if the two strings are equal, a negative value if the first string is less than the second, and a positive value if the first string is greater than the second.

#include <stdio.h>

#include <string.h>

int main() {

char str1[] = "apple";

char str2[] = "banana";

int result = strcmp(str1, str2);

if (result == 0) {

printf("Strings are equal.\n");

} else if (result < 0) {

printf("str1 is less than str2.\n");

} else {

printf("str1 is greater than str2.\n");

}

return 0;

}


Output:

str1 is less than str2.

  1. strcpy() (String Copy):

  • The strcpy() function is used to copy one string into another. It replaces the contents of the destination string with the source string.

#include <stdio.h>

#include <string.h>

int main() {

char destination[20];

char source[] = "Copy me!";

strcpy(destination, source); // Copy source to destination

printf("Copied string: %s\n", destination);

return 0;

}


Output:

Copied string: Copy me!