string stuff

Hello. So I need to execute a word thats given, but letters have to change their places, 1st letter with 2nd, 3rd one with 4th one... I think I need one more variable?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  


# include <fstream>
# include <iostream>
# include <iomanip>
using namespace std;
int main()
{   int a;
    string s;
    cin >> s;
    int n = s.length();
    n=a;
   for (int i = 0; i < n; i++){
        cout << s[n-(a-1)];
        cout << s[n-a];
        a--;
   }
    return 0;
}
things to note:
1. string might have whitespace, so use getline(), not cin()
2. think of a sufficiently rare character to substitute for whitespace such that this character is not expected to appear in a string
3. decide how to handle odd/even string size - I have made an assumption as the code shows but you can substitute your own
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
    string inputString;
    cout<<"Enter string: \n";
    getline(cin, inputString);

    for(std::string::size_type i = 0; i < inputString.size(); ++i)
    {
        if(inputString[i] == ' ')
        {
            inputString[i] = '*';
        }
    }
    if(inputString.size()%2==0)
    {
        for(std::string::size_type i = 0; i < inputString.size(); i +=2)
        {
            swap(inputString[i], inputString[i+1]);
        }
    }
    else
    {
        for(std::string::size_type i = 0; i < inputString.size()-1; i += 2 )
        {
            swap(inputString[i], inputString[i+1]);
        }

    }
     for(std::string::size_type i = 0; i < inputString.size(); ++i)
    {
        if(inputString[i] == '*')
        {
            inputString[i] = ' ';
        }
    }
    cout<<"Swapped string: "<<inputString<<"\n";
}

Sample Output
1
2
3
4
5
6
Enter string:
arsenal won today!!
Swapped string: raesan low notad!y!

Process returned 0 (0x0)   execution time : 9.709 s
Press any key to continue.

Actually the program will take care of whitespace itself, we don't need any special code for that. So it is much shorter and more robust:
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
27
28
29
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
    string inputString;
    cout<<"Enter string: \n";
    getline(cin, inputString);

    if(inputString.size()%2==0)
    {
        for(std::string::size_type i = 0; i < inputString.size(); i +=2)
        {
            swap(inputString[i], inputString[i+1]);
        }
    }
    else
    {
        for(std::string::size_type i = 0; i < inputString.size()-1; i += 2 )
        {
            swap(inputString[i], inputString[i+1]);
        }
    }
   cout<<"Swapped string: "<<inputString<<"\n";
}
Topic archived. No new replies allowed.