Operating System - OpenVMS
1751709 Members
5258 Online
108781 Solutions
New Discussion юеВ

C++ SWAP function - help

 
SOLVED
Go to solution
Boniface Chiwenda
Occasional Contributor

C++ SWAP function - help

Hi every one
I have a problem writting a function which should
be able to output characters which are swapped i.e give then the input 'HELLOW WORLD'
the output should be 'EHLLWO OWLRD' can some one help.

Regards
Bonnie.
3 REPLIES 3
Hein van den Heuvel
Honored Contributor

Re: C++ SWAP function - help

What is the exat problem you are having?
What do you want the swap to do when there is an odd number of characters?

Here is something to get you going.
Works for me (with TWO spaces betweeb HELLOW and WORLD"

#include

swap (char *string_pointer)
{
short temp, *short_pointer;
char c, *p;

p = string_pointer;
short_pointer = (void *) p;
while (*p) {
c = *p++;
if (*p) {
temp = (c << 8) + *p++;
*short_pointer++ = temp;
}
}
}

main() {
char test[]="HELLOW WORLD";
swap(test);
printf ("%s\n", test);
}

$ cc tmp
$ lin tmp
$ run tmp
EHLLWO OWLRD
$

Boniface Chiwenda
Occasional Contributor

Re: C++ SWAP function - help

Great thanks for your help. If the sentence is
of odd number the last character is not switched with anything, but simply attached.

Regards
Bonnie.
Antoniov.
Honored Contributor
Solution

Re: C++ SWAP function - help

Hi Hein,
sorry for disagree another time inthe same week :-o (never happened before!)

Your code is quick but assume short as 16 bit that's is true in current C/C++ but may be false in future (or on other systems).
Also you assume char as 8 bit so your code can't work with wchar (known as unicode).

This code is slower but more secure and more flexible:

swap (char *string_pointer)
{
char c, *p, *p1;

p = string_pointer;
while (*p)
{
p1 = p;
c = *p++;
if (*p)
{
*p1 = *p;
*p = c;
}
}
}

Changing in above code 'char' with 'wchar' function can work using unicode.

Regards
Antonio Vigliotti
Antonio Maria Vigliotti