I'm a beginner in C++ and I want to code a simple program which swaps two characters in a string.
For example; we input this string : "EXAMPLE" and we give it these two characters to swap : 'E' & 'A' and the output should be something like "AXEMPLA".
The algorithm that I consider while writing the following piece of code; is pretty simple and I hope you'll get it by referring to the code, but I got confused at the end! (I did searches in this website and found similar questions, but they were either difficult and complex syntax or in another language). Any suggestions and help are appreciated.
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <cctype> // is this necessary?! I doubt between <stodio.h> and <cctype>
// By the way! when do we use double quotations instead of <> ?
using namespace std;
char array1[30], char1, char2;
int i, j, char1count = 0, char2count = 0, locofchar1[15], locofchar2[15], n1 = 0, n2 = 0;
int main()
{
cout << "Enter your string: " << endl;
gets(array1);
cout << "\nEnter the 2 characters you want to swap." << endl
<< "Character #1: ";
cin >> char1;
cout << "\nCharacter #2: ";
cin >> char2;
for (i = 0; array1[i]; i++) // A "for" loop for counting the number of repetitions of char1
// and saving the locations of char1 in a new array called "locofchar1"
if (array1[i] == char1){
char1count++;
for (j = n1; j <= char1count; j++)
locofchar1[j] = i;
n1++;
}
for (i = 0; array1[i]; i++) // Another "for" loop for counting the number of repetitions of char2
// and saving the locations of char1 in a new array called "locofchar2"
if (array1[i] == char2)
char2count++;
for (j = n2; j <= char2count; j++)
locofchar2[j] = i;
n2++;
/*
I'm already stuck at here! and I think I have some problems in the above code... We assume that the program determined the number of repetitions and their element address/location in the char1count and char2count arrays, and we want to use this informations to swap them correctly.
*/
getch();
return 0;
}