0

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;
}
PsychoMotel
  • 9
  • 2
  • 5

4 Answers4

3

You forgot to put brackets in several locations.

  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++;

Without curly brackets, in C/C++, only the first procedure after the if is under the condition. The rest are executed unconditionally. So the for loop in the code above is executed every time. So add curly brackets:

       if (array1[i] == char2) {
          char2count++;
          for (j = n2; j <= char2count; j++) {
              locofchar2[j] = i;
              n2++;
          }
       }

It is good practice to add curly brackets for every condition and every loop, so that you don't forget which lines fall under those conditions/loops.

G. Ko
  • 403
  • 6
  • 15
0

Your code is too complicated and as any complicated code contains bugs.

Try the following approach to write the loop

#include <iostream>

int main()
{
    char s[] = "EXAMPLE";
    char c1 = 'A', c2 = 'E';

    std::cout << s << std::endl;

    for ( char *p = s; *p; ++p )
    {
        if ( *p == c1 ) *p = c2;
        else if ( *p == c2 ) *p = c1;
    }

    std::cout << s << std::endl;
}

The program output is

EXAMPLE
AXEMPLA

There is a principle in programming named KISS - Keep It Simple, Stupid.:) The simpler code the easier to understand what it does.

Take into account that you should use C++ input funcions. It would be better if instead of C function gets which is unsafe you would use standard C++ function getline

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Thank you, what does *p means? – PsychoMotel Mar 10 '15 at 08:30
  • @PsychoMotel This statement char *p = s; declares a pointer that is initialized by the address of the first character of character array s. This expression *p; is equivalent to expression *p != '\0'; that is there is a check whether the current character is the zero terminating character or not. Take into account that if an expression has value 0 or '\0' then it is implicitly converted to false in conditions. – Vlad from Moscow Mar 10 '15 at 08:33
0
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str = "";
    char firstChar, secondChar;

    cout << "Enter a string: ";
    getline(cin, str);

    cout << "\nEnter two characters to swap\n";

    cout << "First character: ";
    cin >> firstChar;
    cout << "Second character: ";
    cin >> secondChar;

    for (unsigned char counter = 0; counter < str.size(); counter++)
    {
        if (str[counter] == firstChar)
        {
            str[counter] = secondChar;  // Swap every instance of first
                                        // character with second character.
        }
        else if (str[counter] == secondChar)
        {
            str[counter] = firstChar;  // Swap every instance of second
                                       // character with first character.
        }
    }

    cout << "Result: " << str << endl;

    return 0;
}

You don't need stdio, conio and cctype. iostream and string is enough for this C++ program. You are mixing C and C++ by adding stdio and conio.

About this:

// By the way! when do we use double quotations instead of <> ?

Visit this link for the answer.

Community
  • 1
  • 1
Ryklon Zen
  • 173
  • 1
  • 3
  • 19
  • Your program is wrong because the loop can be infinite in case when the size of the string is greater than std::numeric_limits::max().:) – Vlad from Moscow Mar 10 '15 at 08:27
0

Does this look helpful, have a nice day.

#include <string>
#include <algorithm>

std::string s = "03/02";
std::swap(s[1], s[4]);
Shyam Bhimani
  • 1,310
  • 1
  • 22
  • 37
Dler
  • 54
  • 1
  • 11