Home »
C 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".
Example:
Input:
String: "help"
Output:
String: "ehpl"
Input:
String: "Hello"
Output:
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 : ");
fgest(string,30,stdin);//gets(string);
// calculate the length of the string
length = strlen(string);
if(length%2==0)
{
for(i=0;i<length;i+=2)
{
c = string[i] ;
string[i] = string[i+1];
string[i+1] = c;
}
printf("\nAfter Swap String : %s",string);
}
else
{
printf("\nThe length of the string is Odd..\n");
}
return 0;
}
Output
Run 1:
Enter the string : help
After Swap String : ehpl
Run 2:
Enter the string : program
The length of the string is Odd..
C String Programs »