HPE Community read-only access December 15, 2018
This is a maintenance upgrade. You will be able to read articles and posts, but not post or reply.
Hours:
Dec 15, 4:00 am to 10:00 am UTC
Dec 14, 10:00 pm CST to Dec 15, 4:00 am CST
Dec 14, 8:00 pm PST to Dec 15, 2:00 am PST
Operating System - OpenVMS
cancel
Showing results for 
Search instead for 
Did you mean: 

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