reversing a string - newbie question

Discussion in 'C Programming' started by netforce, Mar 2, 2004.

  1. netforce

    netforce Guest

    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.
    netforce, Mar 2, 2004
    #1
    1. Advertising

  2. netforce wrote:
    > 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
    Bertrand Mollinier Toublet, Mar 2, 2004
    #2
    1. Advertising

  3. netforce

    Mark Henning Guest

    > 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?
    Mark Henning, Mar 2, 2004
    #3
  4. "Mark Henning" <> writes:

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


    --
    ,--. Martin Dickopp, Dresden, Germany ,= ,-_-. =.
    / ,- ) http://www.zero-based.org/ ((_/)o o(\_))
    \ `-' `-'(. .)`-'
    `-. Debian, a variant of the GNU operating system. \_/
    Martin Dickopp, Mar 2, 2004
    #4
  5. netforce

    Mark Henning Guest

    > 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?
    Mark Henning, Mar 2, 2004
    #5
  6. netforce

    pete Guest

    Mark Henning wrote:

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

    --
    pete
    pete, Mar 2, 2004
    #6
  7. "Mark Henning" <> writes:

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


    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


    --
    ,--. Martin Dickopp, Dresden, Germany ,= ,-_-. =.
    / ,- ) http://www.zero-based.org/ ((_/)o o(\_))
    \ `-' `-'(. .)`-'
    `-. Debian, a variant of the GNU operating system. \_/
    Martin Dickopp, Mar 2, 2004
    #7
  8. netforce

    CBFalconer Guest

    Mark Henning wrote:
    >
    >> 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?


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

    --
    Chuck F () ()
    Available for consulting/temporary embedded and systems.
    <http://cbfalconer.home.att.net> USE worldnet address!
    CBFalconer, Mar 2, 2004
    #8
  9. 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>


    >main()


    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"?
    Peter Shaggy Haywood, Mar 6, 2004
    #9
  10. netforce

    Old Wolf Guest

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

    >
    > >main()

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

    >
    > > char str2[40];


    [snip: code that copies str into str2]
    Old Wolf, Mar 8, 2004
    #10
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Albert

    String reversing problem

    Albert, Dec 30, 2005, in forum: C Programming
    Replies:
    46
    Views:
    938
  2. Lindsay
    Replies:
    3
    Views:
    278
    upashu2
    Jul 18, 2005
  3. Michael Jarrod

    Newbie pointers and reversing question

    Michael Jarrod, Apr 15, 2007, in forum: C Programming
    Replies:
    37
    Views:
    730
    Army1987
    Apr 20, 2007
  4. Kelly B

    Reversing order of words in a given string

    Kelly B, Apr 26, 2007, in forum: C Programming
    Replies:
    2
    Views:
    350
    Kelly B
    Apr 26, 2007
  5. Scott

    Reversing a string

    Scott, Jun 27, 2007, in forum: Python
    Replies:
    23
    Views:
    584
    Martin Durkin
    Jul 5, 2007
Loading...

Share This Page