473,791 Members | 3,071 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reverse a string in place

Thanks for the additional comments.

Here is a solution to an exercise I had problems with. I still don't
think it's really what's wanted as it uses a "state variable" n - but
I can't see how to do it without this (or changing the function to
take an extra argument). Thanks for any hints.

#include<stdio. h>

#define SWAP(a,b) { char x; x=(a); (a)=(b); (b)=x; }

void reverse();

main(int argc, char**argv)
{
if(argc>1) {
reverse(argv[1]);
printf("%s\n", argv[1]);
} else
printf("Unspeci fied error\n");
}

void reverse(char *s)
{
static int n=-1;
if(n==-1)
n=strlen(s)-1;
SWAP(*s, s[n]);
if((n-=2)>=0)
reverse(s+1);
else
n=-1; /* make sure function is reentrant */
}
Dec 6 '07 #1
15 6270
On Dec 6, 3:15 pm, raj...@thisisno tmyrealemail.co m wrote:
Thanks for the additional comments.

Here is a solution to an exercise I had problems with. I still don't
think it's really what's wanted as it uses a "state variable" n - but
I can't see how to do it without this (or changing the function to
take an extra argument). Thanks for any hints.
void reverse(char *string)
{
char *end;

for (end = string; *end ; ++end); --end;
/* end points to last character in string */

while (string end)
{
char temp;

temp = *string;
*string++ = *end;
*end-- = temp;
}
}

Dec 6 '07 #2
Oops... pardon my typo...

On Dec 6, 3:28 pm, Lew Pitcher <lpitc...@teksa vvy.comwrote:
On Dec 6, 3:15 pm, raj...@thisisno tmyrealemail.co m wrote:
Thanks for the additional comments.
Here is a solution to an exercise I had problems with. I still don't
think it's really what's wanted as it uses a "state variable" n - but
I can't see how to do it without this (or changing the function to
take an extra argument). Thanks for any hints.

void reverse(char *string)
{
char *end;

for (end = string; *end ; ++end); --end;
/* end points to last character in string */

while (string end)
{
char temp;

temp = *string;
*string++ = *end;
*end-- = temp;
}

}

void reverse(char *string)
{
char *end;

for (end = string; *end ; ++end); --end;
/* end points to last character in string */

while (string < end)
{
char temp;

temp = *string;
*string++ = *end;
*end-- = temp;
}
}
Dec 6 '07 #3
Lew Pitcher wrote:
On Dec 6, 3:15 pm, raj...@thisisno tmyrealemail.co m wrote:
Thanks for the additional comments.

Here is a solution to an exercise I had problems with. I still don't
think it's really what's wanted as it uses a "state variable" n - but
I can't see how to do it without this (or changing the function to
take an extra argument). Thanks for any hints.

void reverse(char *string)
{
char *end;

for (end = string; *end ; ++end); --end;
/* end points to last character in string */

while (string end)
{
char temp;

temp = *string;
*string++ = *end;
*end-- = temp;
}
}
Uhh yes! I should have said clearly that it's Exercise 4.13 - write a
**recursive** version of reverse(s).
Dec 6 '07 #4
ra****@thisisno tmyrealemail.co m wrote:
) Uhh yes! I should have said clearly that it's Exercise 4.13 - write a
) **recursive** version of reverse(s).

That's silly. Reversing a string is clearly an iterative operation.
However, any iteration can be easily transformed into a tail recursion.

Note, also, that it is perfectly valid to have two functions.
One that recurses, and one that makes the initial call to the other.

Anyways, Here's a stab at a very inefficient and silly solution, using
a single function:

void reverse(char *string)
{
size_t len = strlen(string);
if (len 1) {
char tmp = string[len-1];
string[len-1] = 0;
reverse(string + 1);
string[len-1] = string[0];
string[0] = tmp;
}
}
SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
Dec 6 '07 #5
ra****@thisisno tmyrealemail.co m writes:
Thanks for the additional comments.

Here is a solution to an exercise I had problems with. I still don't
think it's really what's wanted as it uses a "state variable" n - but
I can't see how to do it without this (or changing the function to
take an extra argument). Thanks for any hints.

#include<stdio. h>

#define SWAP(a,b) { char x; x=(a); (a)=(b); (b)=x; }
I'd either just write this code out, or I'd make this a function. If
I really needed it to be a macro, I'd use the "do {} while (0)" idiom
so as to get syntactic unit that can be followed by a ; and remain a
single statement.
void reverse();
This is not a prototype for reverse, just a declaration. Tell the
full story by writing:

void reverse(char *s);
main(int argc, char**argv)
int main is better and required in C99.
{
if(argc>1) {
reverse(argv[1]);
printf("%s\n", argv[1]);
} else
printf("Unspeci fied error\n");
}

void reverse(char *s)
{
static int n=-1;
if(n==-1)
n=strlen(s)-1;
SWAP(*s, s[n]);
if((n-=2)>=0)
reverse(s+1);
else
n=-1; /* make sure function is reentrant */
}
Spaces have come right down in price recently after the discovery of
the Peruvian space deposits. Help yourself to a few more.

Reverse is not a natural candidate for recursion (even in functional
languages a little care is needed to stop it being very inefficient)
but in C we have some extra options because we can modify the string.
I'd write it like this:

void rev(char *start, char *end)
{
if (start + 1 >= end)
return;
else {
char t = end[-1];
end[-1] = *start;
*start = t;
rev(start + 1, end - 1);
}
}

void reverse(char *s)
{
rev(s, strchr(s, 0));
}

--
Ben.
Dec 6 '07 #6
Lew Pitcher wrote:
>
Oops... pardon my typo...

On Dec 6, 3:28 pm, Lew Pitcher <lpitc...@teksa vvy.comwrote:
On Dec 6, 3:15 pm, raj...@thisisno tmyrealemail.co m wrote:
Thanks for the additional comments.
Here is a solution to an exercise I had problems with. I still don't
think it's really what's wanted as it uses a "state variable" n - but
I can't see how to do it without this (or changing the function to
take an extra argument). Thanks for any hints.
void reverse(char *string)
{
char *end;

for (end = string; *end ; ++end); --end;
/* end points to last character in string */

while (string end)
{
char temp;

temp = *string;
*string++ = *end;
*end-- = temp;
}

}

void reverse(char *string)
{
char *end;

for (end = string; *end ; ++end); --end;
/* end points to last character in string */
Unless the string is (""),
in which case (end) is undefined.
while (string < end)
{
char temp;

temp = *string;
*string++ = *end;
*end-- = temp;
}
}
--
pete
Dec 7 '07 #7
pete wrote:
Lew Pitcher wrote:
.... snip ...
>
>void reverse(char *string) {
char *end;
for (end = string; *end ; ++end); --end;
/* end points to last character in string */

Unless the string is (""), in which case (end) is undefined.
> while (string < end) {
char temp;

temp = *string;
*string++ = *end;
*end-- = temp;
}
}
So try:

void reverse(char *string) {
char *end, temp;

for (end = string; *end; end++) continue;
/* leaving *end == 0 */
while (string < end) {
temp = *string;
*string++ = *(--end);
*end = temp;
)
} /* reverse, untested */

--
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home .att.net>
Try the download section.

--
Posted via a free Usenet account from http://www.teranews.com

Dec 8 '07 #8
RoS
In data Fri, 14 Dec 2007 12:56:08 -0500, pete scrisse:
what is the difference of the below 2 routines?
>This version of reverse, does nothing:

void reverse(char *string)
{
char *end;

for (end = string; *end ; ++end);
if (*end) --end; else return;
/* end points to last character in string */

while (string < end)
{
char temp;

temp = *string;
*string++ = *end;
*end-- = temp;
}
}
This version of reverse, reverses a string:

void reverse(char *string)
{
char *end;

for (end = string; *end ; ++end);
if (*string) --end; else return;
/* end points to last character in string */

while (string < end)
{
char temp;

temp = *string;
*string++ = *end;
*end-- = temp;
}
}

If you can't see that, then you can't read code anymore.

Nobody else is seeing that code the way that you do.
Dec 14 '07 #9
RoS
In data Fri, 14 Dec 2007 20:53:42 +0100, RoS scrisse:
>In data Fri, 14 Dec 2007 12:56:08 -0500, pete scrisse:
what is the difference of the below 2 routines?
yes i have seen it ...

void reverse(char *aa)
{char *a=aa, *b, t;
if(a==0||*a==0) return;
for( ; *a; ++a);
for(--a, b=aa; b<a; ++b, --a)
{t=*b; *b=*a; *a=t;}
}

this is my version whithout compile it nor debug it
>>This version of reverse, does nothing:

void reverse(char *string)
but str* were not implementation reserved?
>>{
char *end;

for (end = string; *end ; ++end);
if (*end) --end; else return;
when this case "*end!=0" is verified here? (never)

> /* end points to last character in string */

while (string < end)
{
char temp;

temp = *string;
*string++ = *end;
*end-- = temp;
}
}
This version of reverse, reverses a string:

void reverse(char *string)
{
char *end;

for (end = string; *end ; ++end);
if (*string) --end; else return;
/* end points to last character in string */

while (string < end)
{
char temp;

temp = *string;
*string++ = *end;
*end-- = temp;
}
}

If you can't see that, then you can't read code anymore.

Nobody else is seeing that code the way that you do.
Dec 14 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2908
by: Jerry | last post by:
Hi, I want to draw a reverse string, does anyone know how to implement it? And I want to draw a vertical string, it can be implemented by setting StringFormat.StringFormatFlags DirectionVertical, but it's not the effect I expected. I want to get reverse vertical string, like the number of MS Word vertical ruler. How to implement it?
0
1810
by: Alan T | last post by:
I have a string to execute: myExe.exe %1 %2 How do I use in System.Diagnostics.Process.Start? System.Diagnostics.Process.Start("myExe.exe", ........)
9
11905
by: HELLO $$$ | last post by:
From Beginner : I am studying a C++ program, using: char, arrays, etc. The aim of this program is to let it make "Reverse" of any statement (string) as example: if the original string is " this is test " ; the output of the program is reversing this statement to be " tset si siht ". so the string became reversed. I am asking: 1- why some of programmers do this ? 2- What's the benefit if they do this ? at any circumstances? Thank to all.
11
5003
by: Dustan | last post by:
Is there any builtin function or module with a function similar to my made-up, not-written deformat function as follows? I can't imagine it would be too easy to write, but possible... 'I am coding, and he coded last week.' ('coding', 'coded', 'week') expanded (for better visual): ('coding', 'coded', 'week')
38
2729
by: ssecorp | last post by:
char* reverse(char* str) { int length = strlen(str); char* acc; int i; for (i=0; i<=length-1; i++){ acc = str; } return acc; }
0
9515
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10427
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10207
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9995
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7537
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6776
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5559
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3718
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2916
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.