How to swap adjacent characters of a string in C++

1 Answer

0 votes
#include <iostream>

void swap_adjacent_characters(std::string& str) {
    int length = str.length();

	if (length % 2 == 0) {
		for (int i = 0; i < length; i += 2) {
			char ch = str[i] ; 
			str[i] = str[i + 1];  
			str[i + 1] = ch;
		}
	}
}

int main(void) {
    std::string str = "ABCDEFGH"; 

	swap_adjacent_characters(str);
	
	std::cout << str;
}




/*
run:

BADCFEHG

*/

 



answered Dec 26, 2023 by avibootz

Related questions

...