Related Articles
C program to swap adjacent characters of a String
• Last Updated : 07 May, 2020

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
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach:

1. Check if the length of the string is even or odd.
2. If the length is odd, swapping cannot be done.
3. 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 program to swap``// adjacent characters of a String`` ` `#include ``#include `` ` `// 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;``}`
Output:
```eGke
NA
```

Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.

My Personal Notes arrow_drop_up