reversing a string - newbie question

N

netforce

Hi,
I am a newbie trying to learn c programming language.
I am writing a program to reverse a string and printout the result. The
following isthe program.But I am not getting any output while trying to
print.Somebody help me
#include<stdio.h>
#include<string.h>
main()
{
char str[] ="?lla to tseriaf eht is ohw roriM roriM";
char str2[40];
char *p;
int i;
clrscr();
p=str2;
printf("\n\nthe given string is %s\n\n ",str);
for(i=(strlen(str));i>=0;i--)
{
*p=str;
printf("%c",*p);
p++;
}
*p='\0';
printf("\n\nThe reversed string is%s",str2);
getch();
}

the contents of str2 are not getting printed.
I am using a turbo c++ compiler 3.0.
 
B

Bertrand Mollinier Toublet

netforce said:
Hi,
I am a newbie trying to learn c programming language.
I am writing a program to reverse a string and printout the result. The
following isthe program.But I am not getting any output while trying to
print.Somebody help me
"To the rescue. Here I am"
#include<stdio.h>
#include<string.h>
main()
It does not hurt to explicitly indicate the return type for main: int.
{
char str[] ="?lla to tseriaf eht is ohw roriM roriM";
^
Your error is right here. This 't' should be an 'f'.
char str2[40];
char *p;
int i;
clrscr();
p=str2;
printf("\n\nthe given string is %s\n\n ",str);
for(i=(strlen(str));i>=0;i--)
Careful ! The last character of your string actually sits at index
strlen(str)-1 instead of just strlen(str).
{
*p=str;
printf("%c",*p);
p++;
}
*p='\0';
printf("\n\nThe reversed string is%s",str2);
getch();
}

the contents of str2 are not getting printed.

Well, it actually is. However, the first character of str2 in your
version is the nul character (sitting at index strlen(str) in the
original string) which indicates... the end of your string. Whatever
comes after it is not processed by your printf call.

--
Bertrand Mollinier Toublet
"In regard to Ducatis vs. women, it has been said: 'One is a sexy thing
that you've just got to ride, even if it breaks down a lot, costs a lot
of money, and will probably try to kill you'. However, nowadays I can't
seem to remember which one is which." -- Peer Landa
 
M

Mark Henning

for(i=(strlen(str));i>=0;i--)

As an aside, i usually loop through a string using:

for(i = 0; str != '\0'; i++)

I tend to believe that this may be slightly more efficient because it
eliminates the small overhead inherent in the calling of strlen(), but i may
be wrong. Are there any reasons why strlen should be used instead?
 
M

Martin Dickopp

Mark Henning said:
for(i=(strlen(str));i>=0;i--)

As an aside, i usually loop through a string using:

for(i = 0; str != '\0'; i++)

I tend to believe that this may be slightly more efficient


More efficient than what? You cannot compare the efficiency of your loop
to the other one, as they do different things. Yours iterates through
the string in forward direction, while the other iterates through the
string in reverse direction.

Martin
 
M

Mark Henning

More efficient than what? You cannot compare the efficiency of your loop
to the other one, as they do different things. Yours iterates through
the string in forward direction, while the other iterates through the
string in reverse direction.

You misunderstand me.

I was not comparing it to the loop of the OP, since my method will work only
when incrementing i, as you point out. Seeing strlen() used in a for loop to
pass through a string prompted me to ask the question, off-topic as it is.

I will rephrase the question for your benefit.

Are there any benefits to computing the string length using strlen() in
order to loop through a string rather than merely incrementing the pointer
until the NUL character is found?
 
P

pete

Mark said:
I will rephrase the question for your benefit.

Are there any benefits to computing the string
length using strlen() in order to loop through a string
rather than merely incrementing the pointer
until the NUL character is found?


For short string lengths like zero or one,
your way would probably be faster (maybe not), but
there is also a possibility that strlen might be written in assembly
language and might take advantage of opcodes that the compiler
wouldn't normally associate with your source code,
which could pay off on long strings (and again, maybe not).

Either way is fine.
 
M

Martin Dickopp

Mark Henning said:
You misunderstand me.

Apparently I did. Sorry.
I was not comparing it to the loop of the OP, since my method will work only
when incrementing i, as you point out. Seeing strlen() used in a for loop to
pass through a string prompted me to ask the question, off-topic as it is.

I will rephrase the question for your benefit.

Are there any benefits to computing the string length using strlen() in
order to loop through a string rather than merely incrementing the pointer
until the NUL character is found?

Since `strlen' has to iterate through the string to find its length, it
would most likely be wasteful to call `strlen' if you want to use the
result to forward iterate through the string. Effectively, you would
iterate through it twice instead of once.

While the OP could not avoid to iterate through the string twice, you
can and should avoid it if you only want to iterate in forward
direction.

Martin
 
C

CBFalconer

Mark said:
You misunderstand me.

I was not comparing it to the loop of the OP, since my method
will work only when incrementing i, as you point out. Seeing
strlen() used in a for loop to pass through a string prompted
me to ask the question, off-topic as it is.

I will rephrase the question for your benefit.

Are there any benefits to computing the string length using
strlen() in order to loop through a string rather than merely
incrementing the pointer until the NUL character is found?

Yes, as in the following, which only iterates over less than half
the string length.

/* ======================= */
/* reverse string in place */
/* return length of string */
size_t revstring(char *stg)
{
char *last, temp;
size_t lgh;

lgh = strlen(stg);
if (lgh > 1) {
last = stg + lgh; /* points to '\0' */
while (--last > stg) {
temp = *stg; *stg++ = *last; *last = temp;
}
}
return lgh;
} /* revstring */
 
P

Peter Shaggy Haywood

Groovy hepcat netforce was jivin' on Tue, 02 Mar 2004 01:30:27 GMT in
comp.lang.c.
reversing a string - newbie question's a cool scene! Dig it!
I am a newbie trying to learn c programming language.
I am writing a program to reverse a string and printout the result. The
following isthe program.But I am not getting any output while trying to
print.Somebody help me

Even before I looked at your code, I had a strong suspicion about
what you're doing wrong; and I was right.
It's not correct to say you're not getting output. You *are* getting
output, but it's blank. See below.
#include<stdio.h>
#include<string.h>

int main(void)
{
char str[] ="?lla to tseriaf eht is ohw roriM roriM";

You mean this? :)

char str[] = "?lla meht fo tseriaf eht si ohw "
",llaw eht no rorriM ,rorriM";
char str2[40];
char *p;
int i;

Include some white space in your code to make it easier to read.
Poor code formatting can render it illegible.
clrscr();

Non-standard, non-portable, undeclared function which is not even
needed.
p=str2;
printf("\n\nthe given string is %s\n\n ",str);
for(i=(strlen(str));i>=0;i--)

You're starting from the null character at the end of the string.
str[strlen(str)] == '\0'. See below.
{
*p=str;
printf("%c",*p);
p++;
}


Inconsistent indentation. This leads, again, to illegible code.
*p='\0';
printf("\n\nThe reversed string is%s",str2);
getch();

Non-standard, non-portable, undeclared function which is not even
needed.
You should return a value. Remember, main() returns an int, so
return an int. Portable return values for main() are 0, EXIT_SUCCESS
and EXIT_FAILURE (the latter two being macros defined in stdlib.h).

return 0;
}

the contents of str2 are not getting printed.

Yes they are. You're just reversing the whole thing including the
terminating null character, so you're getting a string *beginning*
with a null character. And this is the cause of your output being
blank.

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technically correct" English; but since when was rock & roll "technically correct"?
 
O

Old Wolf

I am a newbie trying to learn c programming language.
I am writing a program to reverse a string and printout the result. The
following isthe program.But I am not getting any output while trying to
print.Somebody help me

Even before I looked at your code, I had a strong suspicion about
what you're doing wrong; and I was right.
#include<stdio.h>
#include<string.h>

int main(void)
{
char str[] ="?lla to tseriaf eht is ohw roriM roriM";

You mean this? :)

char str[] = "?lla meht fo tseriaf eht si ohw "
",llaw eht no rorriM ,rorriM";

I doubt it; your change causes Undefined Behaviour, and the
original code was well-defined except for the "clrscr" and "getch".

[snip: code that copies str into str2]
 

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

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,266
Latest member
DavidaAlla

Latest Threads

Top