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

R

rajendra.stalekar

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

Ravi Uday

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;
}
 
P

Puneet

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^=str[j];
str[j]^=str;
str^=str[j];
}

puts (str);
 
W

Walter Roberson

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^=str[j];
str[j]^=str;
str^=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
 
R

Richard Bos

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
 
E

Eric Sosman

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);
 
D

Default User

Puneet said:
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^=str[j];
str[j]^=str;
str^=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
 
N

Netocrat

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

Neil Cerutti

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);
}
 
M

Mac

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

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
 
R

Ravi Uday

Mac said:
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'
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
 
N

Netocrat

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

Steve Summit

rajendra.stalekar said:
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.
 
J

Jordan Abel

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

Steve Summit

Jordan said:
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.
 
A

ashu

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;
name = name[len]
name[len] = tmp;
}
}
 
N

Neil Cerutti

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

Mac

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top