C program to swap adjacent characters of a String
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 = "geeks" Output: egek
Approach:
- Check if the length of the string is even or odd.
- If the length is even, swapping cannot be done.
- If the length is odd, 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 program to swap // adjacent characters of a String #include <stdio.h> #include <string.h> // Function to swap adjacent characters void swap(char* str) { char c = 0; int length = 0, i = 0; // Find the length of the string length = strlen(str); // Check if the length of the string // is even or odd if (length % 2 == 0) { // swap the characters with // the adjacent character for (i = 0; i < length; i += 2) { c = str[i]; str[i] = str[i + 1]; str[i + 1] = c; } // Print the swapped character string printf("%s\n", str); } else { // Print NA as the string length is odd printf("NA\n"); } } // Driver code int main() { // Get the string char str1[] = "Geek"; char str2[] = "Geeks"; swap(str1); swap(str2); return 0; } |
chevron_right
filter_none
Output:
eGke NA
Recommended Posts:
- Permutation of a string with maximum number of characters greater than its adjacent characters
- Rearrange the characters of the string such that no two adjacent characters are consecutive English alphabets
- String with k distinct characters and no same characters adjacent
- Swap characters in a String
- Rearrange characters in a string such that no two adjacent are same
- Swap all occurrences of two characters to get lexicographically smallest string
- Rearrange characters in a string such that no two adjacent are same using hashing
- Java program to swap first and last characters of words in a sentence
- Minimum replacements to make adjacent characters unequal in a ternary string
- Minimum replacements to make adjacent characters unequal in a ternary string | Set-2
- Program to toggle all characters in a string
- Program to check if first and the last characters of string are equal
- Python program to check if a string contains all unique characters
- Program to print characters present at prime indexes in a given string
- Program to find the product of ASCII values of characters in a string
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


