What are strings? Write a C program to swap two strings

5.C) What are strings? Write a C program to swap two strings

Answer:-

Definition of String :-

“String is a variable-length data stored in a character array”.

  • In C a string is a data structure based on an array of char.
  • A string is a sequence of elements of the char data type.
  • There is no separate data type called a string in the C language.
  • As strings are variable-size data we have to represent them using character Arrays.

An example string is:

C program to swap two strings: –

#include<stdio.h>
#include<string.h>
main(){
   char s1[10],s2[10],s3[10];
   printf("Enter String 1\n");
   gets(s1);
   printf("Enter String 2\n");
   gets(s2);
   printf("Before Swapping\n");
   printf("String 1 : %s\n",s1);
   printf("String 2 : %s\n",s2);
   strcpy(s3,s1);
   strcpy(s1,s2);
   strcpy(s2,s3);
   printf("After Swapping:\n");
   printf("String 1 : %s\n",s1);
   printf("String 2 : %s\n",s2);
}

output:-
Enter String 1
VTU
Enter String 2
Updates
Before Swapping
String 1: VTU
String 2: Updates
After Swapping:
String 1: Updates
String 2: VTU

Leave a Reply

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