C program to swap adjacent characters of a String
Last Updated :
09 Jun, 2022
Given a string str, the task is to swap adjacent characters of this string in C. Examples:
Input: str = "geeks"
Output: NA
Not possible as the string length is odd
Input: str = "geek"
Output: egke
Approach:
- Check if the length of the string is even or odd.
- If the length is odd, swapping cannot be done.
- If the length is even, take each character of the string one by one and swap it with the adjacent character.
Below is the implementation of the above approach:
C
#include <stdio.h>
#include <string.h>
void swap( char * str)
{
char c = 0;
int length = 0, i = 0;
length = strlen (str);
if (length % 2 == 0) {
for (i = 0; i < length; i += 2) {
c = str[i];
str[i] = str[i + 1];
str[i + 1] = c;
}
printf ("%s\n", str);
}
else {
printf ("NA\n");
}
}
int main()
{
char str1[] = "Geek";
char str2[] = "Geeks";
swap(str1);
swap(str2);
return 0;
}
|
Time complexity: O(length(str))
Auxiliary space: O(1)
Share your thoughts in the comments
Please Login to comment...