swap letters in string

hi guys, so im building a function that swap every two lettres in a string.
for example, "abcdef" will be "badcfe".

i can't use: pointers and built in system functions.

This is my code. Sadly the function returns the exact word. why is that so?
hope you can share your knowledge with me!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<iostream>
using namespace std;
int const SIZE = 100;

void switchLetters(char s[]) {
	
	char swap;
	int i;

	for (i = 0; i < SIZE && i != NULL; i++) {
		swap = s[i];
		s[i] = s[i + 1];
		s[i + 1] = swap;
	}
	cout << s;
}

int main() {

	char s[SIZE];
	cin.getline (s, 100);
	
	switchLetters(s);

	system("pause");
}
Last edited on
You swap each pair of letters ... and then immediately swap them back.

For C-strings of even length you can change line 10 to
for (i = 0; i < SIZE - 1 && s[i] != NULL && s[i+1] != NULL; i += 2) {

Note the comparing of s[i] and s[i+1] rather than i with NULL, and incrementing by 2 each time rather than 1 (which would simply swap the letters back).

You will have to decide what you actually want to do with odd-length strings.

The slightly abbreviated form
for (i = 0; i < SIZE - 1 && s[i] && s[i+1] ; i += 2) {
will also work.


Personally, I think it more logical to leave the function to do the switching and then put the final cout << s; in main().
Last edited on
thanks very much!!!
Try this.

// Java program to demonstrate character swap
// using toCharArray().
public class GFG {
static char[] swap(String str, int i, int j)
{
char ch[] = str.toCharArray();
char temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
return ch;
}

public static void main(String args[])
{
String s = "geeksforgeeks";

System.out.println(swap(s, 6, s.length() - 2));
System.out.println(swap(s, 0, s.length() - 1));

System.out.println(s);
}
}
@sp356069, that is great; however, the language is C++ and not Java.
Topic archived. No new replies allowed.