Home » C solved programs » C string programs

C program to swap adjacent characters of a string

In this C program, we are going to learn how to swap adjacent characters of a string? Here, we will have a string with even number of characters (string length must be even to swap the adjacent characters).
Submitted by IncludeHelp, on April 05, 2018

Given a string and we have to swap its adjacent characters using C program.

Here, to swap adjacent characters of a given string - we have a condition, which is "string length must be EVEN i.e. string must contains even number of characters".


    String: "help"
    String: "ehpl"

    String: "Hello"
    The length of the string is Odd..

Program to swap adjacent characters of a string in C

/** C program to swap adjacent characters 
* of a string but obly if it is of even 
* length

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

// main function
int main()
	// Declare an integer pointer
	char string[30]={0};
	char c=0;
	int length=0,i=0;

	// Take string input from the user
	printf("\nEnter the string : ");

	// calculate the length of the string
	length = strlen(string);

			c = string[i] ; 
			string[i] = string[i+1];  
			string[i+1] = c;
		printf("\nAfter Swap String : %s",string);
		printf("\nThe length of the string is Odd..\n");
	return 0;


    Run 1: 
    Enter the string : help
    After Swap String : ehpl

    Run 2:
    Enter the string : program
    The length of the string is Odd..

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.

Comments and Discussions

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com (2015-2018), Some rights reserved.

close Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.