By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,507 Members | 1,758 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,507 IT Pros & Developers. It's quick & easy.

How do I reverse a string with a single variable for swapping

P: n/a
Hi Folks!!!
I have a string let's say "hi" and got to reverse it using just a
single variable for swapping, how do I do it?

Regards,
Rajendra S.

Nov 15 '05 #1
Share this Question
Share on Google+
28 Replies


P: n/a
ra***************@gmail.com writes:
I have a string let's say "hi" and got to reverse it using just a
single variable for swapping, how do I do it?


Is this homework?

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #2

P: n/a

Sounds trivial
Dont know if i got that right
used only 1 var 'newvar'

#include <stdio.h>

int main()
{
char main[2] = "hi";
char newvar[2] = "0";

newvar[0] = main[1];
newvar[1] = main[0];

printf ("%s\n", newvar);
return 0;
}
ra***************@gmail.com wrote:
Hi Folks!!!
I have a string let's say "hi" and got to reverse it using just a
single variable for swapping, how do I do it?

Regards,
Rajendra S.


Nov 15 '05 #3

P: n/a
I think you want this,

char *str="hello";
int i,j,k;
k=strlen(str)-1;
for (i=0, j=k; i<k/2; i++,j--) {
str[i]^=str[j];
str[j]^=str[i];
str[i]^=str[j];
}

puts (str);

Nov 15 '05 #4

P: n/a
In article <11*********************@g14g2000cwa.googlegroups. com>,
Puneet <mr*************@gmail.com> wrote:
I think you want this,
Who wants what? Context, please!!

char *str="hello";
int i,j,k;
k=strlen(str)-1;
for (i=0, j=k; i<k/2; i++,j--) {
str[i]^=str[j];
str[j]^=str[i];
str[i]^=str[j];
} puts (str);


That code does not appear to meet the criteria of using only
a single variable for swapping. I count 3 variables there: i, j, k

--
Chocolate is "more than a food but less than a drug" -- RJ Huxtable
Nov 15 '05 #5

P: n/a
ra***************@gmail.com wrote:
I have a string let's say "hi" and got to reverse it using just a
single variable for swapping, how do I do it?


You don't. In the general case, you need at least two counters and/or
pointers plus swap space for a single element. If you have shortcuts,
you're not talking about "a string let's say" any more.

Richard
Nov 15 '05 #6

P: n/a
On 2005-10-27, Walter Roberson <ro******@ibd.nrc-cnrc.gc.ca> wrote:
In article <11*********************@g14g2000cwa.googlegroups. com>,
Puneet <mr*************@gmail.com> wrote:
I think you want this,


Who wants what? Context, please!!

char *str="hello";
int i,j,k;
k=strlen(str)-1;
for (i=0, j=k; i<k/2; i++,j--) {
str[i]^=str[j];
str[j]^=str[i];
str[i]^=str[j];
}

puts (str);


That code does not appear to meet the criteria of using only
a single variable for swapping. I count 3 variables there: i, j, k


Yes, but none of them are used for swapping.
Nov 15 '05 #7

P: n/a


ra***************@gmail.com wrote On 10/27/05 02:29,:
Hi Folks!!!
I have a string let's say "hi" and got to reverse it using just a
single variable for swapping, how do I do it?


Answer #1 (which improves on the suggested solution
by using *no* variables for swapping!):

char string[] = "hi";
string[0] = 'i';
string[1] = 'h';

Answer #2 (a more general approach):

char string[] = "hi";
char *p = calloc(strlen(string) + 1, sizeof(char));
if (p == NULL)
abort();
while (strlen(p) < strlen(string)) {
memcpy(strchr(p, string[strlen(string)],
strchr(string, p[strlen(p)] - strlen(p) - 1,
sizeof p / sizeof(&string[0]));
}
strcpy (string, p);
free (p);

--
Er*********@sun.com

Nov 15 '05 #8

P: n/a
Puneet wrote:
I think you want this,

char *str="hello";
int i,j,k;
k=strlen(str)-1;
for (i=0, j=k; i<k/2; i++,j--) {
str[i]^=str[j];
str[j]^=str[i];
str[i]^=str[j];
}


This modifies a string literal. That's undefined behavior.

Define str like this:

char str[] = "hello";
See the FAQ for more details.

Brian

--
Please quote enough of the previous message for context. To do so from
Google, click "show options" and use the Reply shown in the expanded
header.
Nov 15 '05 #9

P: n/a
On Thu, 27 Oct 2005 10:54:54 -0400, Eric Sosman wrote:
ra***************@gmail.com wrote On 10/27/05 02:29,:
Hi Folks!!!
I have a string let's say "hi" and got to reverse it using just a
single variable for swapping, how do I do it?
[...] char string[] = "hi";
char *p = calloc(strlen(string) + 1, sizeof(char));
if (p == NULL)
abort();
while (strlen(p) < strlen(string)) {
memcpy(strchr(p, string[strlen(string)],
strchr(string, p[strlen(p)] - strlen(p) - 1,
sizeof p / sizeof(&string[0]));
}
strcpy (string, p);
free (p);


I think the fact there's so little obfuscation makes it even more
obfuscated.

I also think you didn't intend for two closing parentheses to be
missing.

--
http://members.dodo.com.au/~netocrat
Nov 15 '05 #10

P: n/a
On 2005-10-27, ra***************@gmail.com
<ra***************@gmail.com> wrote:
Hi Folks!!!
I have a string let's say "hi" and got to reverse it using just
a single variable for swapping, how do I do it?


Assuming s points to "hi":

Here's a quick implementation that only uses one variable, p, for
swapping.

void reverse(char *s)
{
char *p = calloc(sizeof *s, strlen(s)+2);
*p = *p + 1;
while (*p)
{
p = p + 1;
*p = *s;
s = s + 1;
}
s = s - 1;
p = p - 1;
*p = *p - 1;
while (*p)
{
*p = *p + 1;
p = p - 1;
*p = *p - 1;
}
*p = *p + 1;
p = p + 1;
while (*p)
{
s = s - 1;
*s = *p;
p = p + 1;
}
p = p - 1;
*p = *p - 1;
while (*p)
{
*p = *p + 1;
p = p - 1;
*p = *p - 1;
}
free(p);
}

--
Neil Cerutti
Nov 15 '05 #11

P: n/a
Mac
On Thu, 27 Oct 2005 12:28:08 +0530, Ravi Uday wrote:

Sounds trivial
Dont know if i got that right
used only 1 var 'newvar'

#include <stdio.h>

int main()
This is bad form. Try:
int main(void)
{
char main[2] = "hi";
It is bad form to use the variable name "main" inside function main().
Also, main should have size 3, not 2:

char main[3] = "hi";
char newvar[2] = "0";
ditto:
char newvar[3];

newvar[0] = main[1];
newvar[1] = main[0];
Add:
newvar[2] = '\0';

printf ("%s\n", newvar);
That last one is an actual bug. You can't pass newvar to printf() with
the %s format unless you put a terminating 0 at the end of newvar.
return 0;
}
ra***************@gmail.com wrote:
Hi Folks!!!
I have a string let's say "hi" and got to reverse it using just a
single variable for swapping, how do I do it?

Regards,
Rajendra S.


By the way, Ravi, please don't top-post. It forces others to read the
conversation out of order.

Also, it is a good idea to compile and run programs before posting them.
This helps avoid embarrassing mistakes. Of course, normal mortals make
mistakes all the time, but that doesn't make them any less embarrassing. ;-)

--Mac

Nov 15 '05 #12

P: n/a


Mac wrote:
On Thu, 27 Oct 2005 12:28:08 +0530, Ravi Uday wrote:

Sounds trivial
Dont know if i got that right
used only 1 var 'newvar'

#include <stdio.h>

int main()

This is bad form. Try:
int main(void)

{
char main[2] = "hi";

It is bad form to use the variable name "main" inside function main().
Also, main should have size 3, not 2:


Agreed my mistake should have been 3.

char main[3] = "hi";

char newvar[2] = "0";

ditto:
char newvar[3];


Agreed my mistake should have been 3

newvar[0] = main[1];
newvar[1] = main[0];

Add:
newvar[2] = '\0';


Nope ! initializing 'newvar' to zero (as in my original post),
initializes all the elements of the array 'newvar' to 0 or '\0'

printf ("%s\n", newvar);

That last one is an actual bug. You can't pass newvar to printf() with


Nope since 'newvar' is declared as char newvar[3] = "0";
all its array elements are initialized to zero :)

C89 -

3.5.7 Initialization

An array of character type may be initialized by a character string
literal, optionally enclosed in braces. Successive characters of the
character string literal (including the terminating null character if
there is room or if the array is of unknown size) initialize the
members of the array.
the %s format unless you put a terminating 0 at the end of newvar.
Right

- Ravi

return 0;
}
ra***************@gmail.com wrote:
Hi Folks!!!
I have a string let's say "hi" and got to reverse it using just a
single variable for swapping, how do I do it?

Regards,
Rajendra S.

By the way, Ravi, please don't top-post. It forces others to read the
conversation out of order.

Also, it is a good idea to compile and run programs before posting them.
This helps avoid embarrassing mistakes. Of course, normal mortals make
mistakes all the time, but that doesn't make them any less embarrassing. ;-)

--Mac


Nov 15 '05 #13

P: n/a
Ravi Uday wrote:
[...]
Nope since 'newvar' is declared as char newvar[3] = "0";
all its array elements are initialized to zero :)
Minor quibble: the first one is initialised to '0' (the
implementation's integral representation of character zero).
C89 -

3.5.7 Initialization

An array of character type may be initialized by a character string
literal, optionally enclosed in braces. Successive characters of the
character string literal (including the terminating null character if
there is room or if the array is of unknown size) initialize the
members of the array.


You might have wanted to complete that reasoning with this later
paragraph (N869):

If there are fewer initializers in a ... string literal used to
initialize an array of known size than there are elements in the array,
the remainder of the aggregate shall be initialized implicitly the same
as objects that have static storage duration.

And this prior paragraph:

If an object that has static storage duration is not initialized
explicitly, then:
....
-- if it has arithmetic type, it is initialized to (positive or
unsigned) zero;

--
http://members.dodo.com.au/~netocrat

Nov 15 '05 #14

P: n/a
rajendra.stalekar writes:
I have a string let's say "hi" and got to reverse it using just a
single variable for swapping, how do I do it?


Can you write code to reverse a string, at all?
If so, good. You could post it, and we might have some
suggestions on how to improve it.

Ignore the ridiculous constraint about "using just a single
variable for swapping". Your instructor is an idiot for imposing
that constraint. The "trick" for using a single variable is one
you would have no reason to know, and which there's no good
reason to learn. Attempting to labor under that constraint would
teach you absolutely nothing useful, and would at worst lure you
into writing significantly suboptimal, broken code.
Nov 15 '05 #15

P: n/a
On 2005-10-28, Steve Summit <sc*@eskimo.com> wrote:
rajendra.stalekar writes:
I have a string let's say "hi" and got to reverse it using just a
single variable for swapping, how do I do it?


Can you write code to reverse a string, at all?
If so, good. You could post it, and we might have some
suggestions on how to improve it.

Ignore the ridiculous constraint about "using just a single
variable for swapping". Your instructor is an idiot for imposing
that constraint. The "trick" for using a single variable is one
you would have no reason to know, and which there's no good reason
to learn. Attempting to labor under that constraint would teach
you absolutely nothing useful, and would at worst lure you into
writing significantly suboptimal, broken code.


I think "single variable for swapping" means he only gets one char
of temp space, not that he can only use one variable total including
iterators etc.
Nov 15 '05 #16

P: n/a
Jordan Abel wrote:
On 2005-10-28, Steve Summit <sc*@eskimo.com> wrote:
Ignore the ridiculous constraint about "using just a single
variable for swapping". Your instructor is an idiot for imposing
that constraint. The "trick" for using a single variable is one
you would have no reason to know, and which there's no good reason
to learn.


I think "single variable for swapping" means he only gets one char
of temp space,


Fair enough. If the original question was to reverse the string
"in place", i.e. without using an additional strlen(str) of space
to build an entirely new string, that's a perfectly good question.
The question I was flaming about (perhaps ill-advisedly) is the
one where you're supposed to swap using 3 obscure XOR's instead
of 3 perfectly normal assignments and a temporary.
Nov 15 '05 #17

P: n/a
complex answers for a simple problem. Solution is:-

int main(void)
{
char *name = "member";
int len = strlen(name);
int i;
len-=1;
char tmp; //single variable
for (i=0; i<=len; i++,--len)
{
tmp = name[i];
name[i] = name[len]
name[len] = tmp;
}
}

Nov 15 '05 #18

P: n/a
On 2005-10-28, Steve Summit <sc*@eskimo.com> wrote:
Jordan Abel wrote:
On 2005-10-28, Steve Summit <sc*@eskimo.com> wrote:
Ignore the ridiculous constraint about "using just a single
variable for swapping". Your instructor is an idiot for
imposing that constraint. The "trick" for using a single
variable is one you would have no reason to know, and which
there's no good reason to learn.


I think "single variable for swapping" means he only gets one
char of temp space,


Fair enough. If the original question was to reverse the
string "in place", i.e. without using an additional strlen(str)
of space to build an entirely new string, that's a perfectly
good question. The question I was flaming about (perhaps
ill-advisedly) is the one where you're supposed to swap using 3
obscure XOR's instead of 3 perfectly normal assignments and a
temporary.


The original question was so imprecise that it's hard to think of
an implementation that doesn't arguably comply.

--
Neil Cerutti
Nov 15 '05 #19

P: n/a
Mac
On Fri, 28 Oct 2005 02:56:06 -0700, Netocrat wrote:
Ravi Uday wrote:
[...]
Nope since 'newvar' is declared as char newvar[3] = "0";
all its array elements are initialized to zero :)


Minor quibble: the first one is initialised to '0' (the
implementation's integral representation of character zero).
C89 -

3.5.7 Initialization

An array of character type may be initialized by a character string
literal, optionally enclosed in braces. Successive characters of the
character string literal (including the terminating null character if
there is room or if the array is of unknown size) initialize the
members of the array.


You might have wanted to complete that reasoning with this later
paragraph (N869):

If there are fewer initializers in a ... string literal used to
initialize an array of known size than there are elements in the array,
the remainder of the aggregate shall be initialized implicitly the same
as objects that have static storage duration.

And this prior paragraph:

If an object that has static storage duration is not initialized
explicitly, then:
...
-- if it has arithmetic type, it is initialized to (positive or
unsigned) zero;


Yes. 3.5.7 (which Ravi supplied) does not, by itself, prove that his
initialization is correct. But with the supplemental text you added, I
think it is safe and correct, (once the size of the array is fixed).

Thanks! (And thanks to you, too, Ravi.)

--Mac

Nov 15 '05 #20

P: n/a
In article <11**********************@f14g2000cwb.googlegroups .com>,
ashu <as*********@gmail.com> wrote:
complex answers for a simple problem. Solution is:-
The solution for what? It's better to quote context, as most of us
do NOT use google groups to read postings.

int main(void)
{
char *name = "member";
int len = strlen(name);
strlen() is not prototyped without <string.h>
int i;
len-=1;
char tmp; //single variable
Using // is not valid in C89.
Making a declaration after an executable statement is not valid in C89.
for (i=0; i<=len; i++,--len)
{
tmp = name[i];
name[i] = name[len]
Missing semicolon is not valid in C89 or C99.
Writing to a string literal is implementation defined in C89 and C99.
name[len] = tmp;
}
Failure to return a value from main is implementation defined in C89.
}
All variables go out of scope at this point, but nothing in this
code has produced any side-effect such as I/O. The compiler could
potentially optimize all the code out entirely.

complex answers for a simple problem. Solution is:-


Looks like that wasn't the solution after all. Was this due to a
misundertanding of the problem, or due to a misunderstanding of how
to program in C ?
--
All is vanity. -- Ecclesiastes
Nov 15 '05 #21

P: n/a
Walter Roberson wrote:
In article <11**********************@f14g2000cwb.googlegroups .com>,
ashu <as*********@gmail.com> wrote:


[snip: Derision of "solution" by ashu]
complex answers for a simple problem. Solution is:-


Looks like that wasn't the solution after all. Was this due to a
misundertanding of the problem, or due to a misunderstanding of how
to program in C ?


Walter, reading your reply, I realised that you have become just
as acerbic as the average clc regular... ;-)

Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 15 '05 #22

P: n/a
In article <3s************@individual.net>,
Michael Mair <Mi**********@invalid.invalid> wrote:
Walter Roberson wrote:
In article <11**********************@f14g2000cwb.googlegroups .com>,
ashu <as*********@gmail.com> wrote:
[snip: Derision of "solution" by ashu]
That wasn't derision, that was pointing out problems.
complex answers for a simple problem. Solution is:-
Looks like that wasn't the solution after all. Was this due to a
misundertanding of the problem, or due to a misunderstanding of how
to program in C ?

Walter, reading your reply, I realised that you have become just
as acerbic as the average clc regular... ;-)
Not yet -- but when someone posts as if they know better than anyone else,
and claims that they have the solution that everyone else has missed,
then they should be right.

Walter, reading your reply, I realised that you have become just
as acerbic as the average clc regular... ;-)


It must be something going around. Even Keith is getting a bit testy lately.
--
Chocolate is "more than a food but less than a drug" -- RJ Huxtable
Nov 15 '05 #23

P: n/a
On 2005-10-28, Steve Summit <sc*@eskimo.com> wrote:
Jordan Abel wrote:
On 2005-10-28, Steve Summit <sc*@eskimo.com> wrote:
Ignore the ridiculous constraint about "using just a single
variable for swapping". Your instructor is an idiot for imposing
that constraint. The "trick" for using a single variable is one
you would have no reason to know, and which there's no good reason
to learn.


I think "single variable for swapping" means he only gets one char
of temp space,


Fair enough. If the original question was to reverse the string
"in place", i.e. without using an additional strlen(str) of space
to build an entirely new string, that's a perfectly good question.
The question I was flaming about (perhaps ill-advisedly) is the
one where you're supposed to swap using 3 obscure XOR's instead
of 3 perfectly normal assignments and a temporary.


You can also do it with addition and subtraction:

x += y; y -= x; x += y; y = -y;

There's a potential of overflow if you're using a signed type, but
then, the XOR version has a potential of a trap representation in an
intermediate step.
Nov 15 '05 #24

P: n/a
Walter Roberson wrote:
In article <11**********************@f14g2000cwb.googlegroups .com>,
ashu <as*********@gmail.com> wrote:


<snip>
int main(void)
{
char *name = "member";
int len = strlen(name);


strlen() is not prototyped without <string.h>
int i;
len-=1;
Ashu could have done the subtraction on the initial assignment of len.
char tmp; //single variable


Using // is not valid in C89.
Making a declaration after an executable statement is not valid in C89.


True. Also, even when using C99 they are a bad idea for Usenet posts
because they do not survive line wrapping.
for (i=0; i<=len; i++,--len)
You missed that this should be i<len not i<=len because there is no
point in swapping a character with itself.

I would not have bothered posting just for this, but since I'm posting
anyway...
{
tmp = name[i];
name[i] = name[len]


Missing semicolon is not valid in C89 or C99.
Writing to a string literal is implementation defined in C89 and C99.


I think you mean undefined behaviour, not implementation defined. One
nice thing about a number of modern C implementations is that this will
actually crash on them, although that is not required of course.

This was the main point of and reason for my post.
name[len] = tmp;
}


Failure to return a value from main is implementation defined in C89.
}


<snip>
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 15 '05 #25

P: n/a
Jordan Abel wrote:
On 2005-10-28, Steve Summit <sc*@eskimo.com> wrote:
The question I was flaming about (perhaps ill-advisedly) is the
one where you're supposed to swap using 3 obscure XOR's instead
of 3 perfectly normal assignments and a temporary.
You can also do it with addition and subtraction:
x += y; y -= x; x += y; y = -y;


"And that way it even works for floating point!"
There's a potential of overflow...


Out of the frying pan, into the fire.
Nov 15 '05 #26

P: n/a
Ravi Uday <ra******@gmail.com> writes:
Mac wrote:
On Thu, 27 Oct 2005 12:28:08 +0530, Ravi Uday wrote: [...]
char main[2] = "hi";

It is bad form to use the variable name "main" inside function
main().
Also, main should have size 3, not 2:


Agreed my mistake should have been 3.


Better yet, let the compiler figure out the size:

char main[] = "hi";

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #27

P: n/a
sc*@eskimo.com (Steve Summit) writes:
rajendra.stalekar writes:
I have a string let's say "hi" and got to reverse it using just a
single variable for swapping, how do I do it?


Can you write code to reverse a string, at all?
If so, good. You could post it, and we might have some
suggestions on how to improve it.

Ignore the ridiculous constraint about "using just a single
variable for swapping". Your instructor is an idiot for imposing
that constraint. The "trick" for using a single variable is one
you would have no reason to know, and which there's no good
reason to learn. Attempting to labor under that constraint would
teach you absolutely nothing useful, and would at worst lure you
into writing significantly suboptimal, broken code.


Just write the natural code, then wrap all the variables in a struct.
It satisfies the stated requirements (unless you consider the struct
members to be variables). And, of course, it's a completely
gratuitous use of a struct.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #28

P: n/a
ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) writes:
In article <3s************@individual.net>,

[...]
Walter, reading your reply, I realised that you have become just
as acerbic as the average clc regular... ;-)


It must be something going around. Even Keith is getting a bit testy lately.


Hey!

Um, never mind. *slinking away*

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #29

This discussion thread is closed

Replies have been disabled for this discussion.