Q:

C program to swap two strings using user define function

0

C program to swap two strings using user define function

Given two strings and we have to swap them using function in C programming language.

In this program, we are not using any library function like strcpy()memcpy() etc, except strlen() - we can also create a function for it. But, the main aim is to swap the strings using function.

Read: C program to implement strlen() function in C

Example:

    Input strings:
    String1: "Hello"
    String2: "World"

    Output:
    String1: "World"
    String2: "Hello"

Here is the function that we are using in the program,

void swapstr(char *str1 , char *str2)

Here,

  • void is the return type
  • swapstr is the name of the string
  • char *str1 is the character pointer that will store the address of given string1 while calling the function
  • char *str2 is the another character pointer that will store the address of given string2 while calling the function

Function calling statement:

swapstr(string1, string2);

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to swap two strings using user define function in C

/** C program to swap two strings using 
 * a user defined function
 */

#include <stdio.h>

// function to swap two strings
void swapstr(char *str1 , char *str2)
{
    char temp;
    int i=0;
    
    for(i=0 ; i<strlen(str1); i++)
    {
        temp = str1[i];
        str1[i] = str2[i];
        str2[i] = temp;
    }
}

// main function
int main()
{
    //Define two char buffers with different strings
    char string1[10]="Hello";
    char string2[10]="World";
    
    swapstr(string1, string2);
    
    printf("\nThe strings are swapping are..\n");
    printf("\nString 1 : %s",string1);
    printf("\nString 2 : %s",string2);

    return 0;
}

Output

The strings are swapping are..
String 1 : World
String 2 : Hello

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
<< C program to pass an array of structure to a user-...