This blog is under construction

Monday 15 July 2013

C program to swap two strings

Write a C program to swap two strings.



  #include <stdio.h>
  #include <string.h>

  int main() {
        char str1[256], str2[256], temp[256];

        /* get the first input string from the user */
        printf("Enter your first input string :");
        fgets(str1, 256, stdin);
        str1[strlen(str1) - 1] = '\0';

        /* get the second input string from the user */
        printf("Enter your sencond input string:");
        fgets(str2, 256, stdin);
        str2[strlen(str2) - 1] = '\0';

        /* string before swapping */
        printf("\nBefore swapping:\n");
        printf("str1 => %s\nstr2 => %s\n", str1, str2);

        /* swap the given input strings */
        strcpy(temp, str1);
        strcpy(str1, str2);
        strcpy(str2, temp);

        /* print the strings after swapping  */
        printf("\nAfter swapping:\n");
        printf("str1 => %s\n", str1);
        printf("str2 => %s\n", str2);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/cpgms/lab_pgms/04_strings$ ./a.out
  Enter your first input string     :Hello
  Enter your sencond input string:World

  Before swapping:
  str1 => Hello
  str2 => World

  After swapping:
  str1 => World
  str2 => Hello


No comments:

Post a Comment