Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
How to Append a Character to a String in C?
Next article icon

C Program to Swap Adjacent Characters of a String

Last Updated : 05 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how to swap adjacent characters of a string in C. To swap all adjacent characters in a string, the string must have an even number of characters. If the number of characters is odd, the last character remains unswapped since it has no adjacent element.

The most straightforward method to swap adjacent characters of a string is by traversing the string using a loop and swapping adjacent character using a temporary variable. Let’s take a look at an example:

C
#include <stdio.h> #include <string.h>  void swap(char *s) {   	int l = strlen(s);   	if (l % 2 != 0) {       	printf("Cannot Swap");       	return;     }        for (int i = 0; i < l; i += 2) {                // Swap using temporary variable         char temp = s[i];         s[i] = s[i+1];         s[i+1] = temp;     } }  int main() {     char s[] = "abcd";          // Swap adjacent characters in the string     swap(s);      printf("%s", s);     return 0; } 

Output
badc

Explanation: In this method, we use a loop to traverse the string two characters at a time. By using array indexing, we can easily access and swap each pair of adjacent characters. The loop ensures that we continue swapping until the end of the string is reached.

There are also a few other methods in C swap adjacent characters of a string. Some of them are as follows:

Using Pointers

This method uses pointer arithmetic to traverse the string, swapping adjacent characters. The pointer moves through the string, swapping pairs of characters, then advances by two positions to compare the next pair.

C
#include <stdio.h> #include <string.h>  void swap(char *s) {        // Continue till a pair exists     while (*s && *(s + 1)) {                 // Swap adjacent characters         char temp = *s;         *s = *(s + 1);         *(s + 1) = temp;                // Move the pointer ahead by two positions to swap the next pair         s += 2;       } } int main() {     char s[] = "abcd";          swap(s);      printf("%s\n", s);     return 0; } 

Output
badcfe 

Using Recursion

The function recursively processes smaller portions of the string, swapping adjacent characters and calling itself to swap the next two characters. This continues until the end of the string or no more pairs remain to be swapped.

C
#include <stdio.h> #include <string.h>  void sHelper(char *s) {        // Swap only when there are two characters left     if (*s && *(s + 1)) {                    char temp = *s;         *s = *(s + 1);         *(s + 1) = temp;          // Recursive call for the next pair of characters         sHelper(s + 2);     } }  void swap(char* s) {   	if (strlen(s) % 2 != 0) {       	printf("Cannot Swap");       	return;     }   	sHelper(s); }  int main() {     char s[] = "abcd";    	// Swap adjacent characters is s     swap(s);      printf("%s", s);     return 0; } 

Output
badcfe


Next Article
How to Append a Character to a String in C?

C

code_r
Improve
Article Tags :
  • C Programs
  • DSA
  • Strings
  • Swap-Program
Practice Tags :
  • Strings

Similar Reads

  • C Program to Sort a String of Characters
    Sorting a string of characters refers to the process of rearranging all the characters in the given order. In this article, we will learn how to sort a string of characters using the C program. The most straightforward method to sort a string of characters is by using the qsort() function. Let's tak
    3 min read
  • How to Append a Character to a String in C?
    In this article, we will learn how to append a character to a string using the C program. The most straightforward method to append a character to a string is by using a loop traverse to the end of the string and append the new character manually. [GFGTABS] C #include <stdio.h> void addChar(ch
    3 min read
  • C Program to print all permutations of a given string
    A permutation also called an "arrangement number" or "order," is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.  Source: Mathword(http://mathworld.wolfram.com/Permutation.html) Below are the permutations o
    2 min read
  • Copy N Characters from One String to Another Without strncat()
    In C, strings are the sequence of characters that are used to represent the textual data. Two strings can be easily concatenated or joined using the strncat() function of the C standard library up to n characters. In this article, we will learn how to concatenate the first n characters from one stri
    2 min read
  • C Program to Concatenate Two Strings Using a Pointer
    Concatenating two strings means appending one string at the end of another string. While the standard library provides strcat() for concatenation, this article will demonstrate how to concatenate two strings using pointers. To concatenate two strings using pointers, traverse the first string to its
    1 min read
  • C Program to Check for Palindrome String
    A string is said to be palindrome if the reverse of the string is the same as the string. In this article, we will learn how to check whether the given string is palindrome or not using C program. The simplest method to check for palindrome string is to reverse the given string and store it in a tem
    4 min read
  • C Program to Split a String into a Number of Sub-Strings
    In this article, we will learn how to split a string into a number of sub-strings using the C program. The most straightforward method to split a string into substrings using a delimiter is by using strtok() function. Let’s take a look at an example: [GFGTABS] C #include <stdio.h> #include
    3 min read
  • How to Convert a String to a Char Array in C?
    In C, the only difference between the string and a character array is possibly the null character '\0' but strings can also be declared as character pointer in which case, its characters are immutable. In this article, we will learn how to convert a string to a char array in C. The most straightforw
    2 min read
  • C Program to Compare Two Strings Using Pointers
    In C, two strings are generally compared character by character in lexicographical order (alphabetical order). In this article, we will learn how to compare two strings using pointers. To compare two strings using pointers, increment the pointers to traverse through each character of the strings whi
    2 min read
  • How to Create a Dynamic Array of Strings in C?
    In C, dynamic arrays are essential for handling data structures whose size changes dynamically during the program's runtime. Strings are arrays of characters terminated by the null character '\0'. A dynamic array of strings will ensure to change it's size dynamically during the runtime of the progra
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences