×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to swap two strings using user define function

In this C program, we are going to learn how to swap two strings without using strcpy()? Here, we will create our own function to swap the strings.
Submitted by IncludeHelp, on March 26, 2018

Problem statement

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

Swapping two strings using user define function

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"

Function Declaration

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

Function calling statement:

swapstr(string1, string2);

Here, string1 and string2 ate the two character arrays (strings), value of string1 is “Hello” and value of string2 is “World”, after function calling the values will be sapped.

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

C User-defined Functions Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.