reversing strings

This is a discussion on reversing strings within the C++ Programming forums, part of the General Programming Boards category; Hi, I found this code in the source section of this web site. My question is this; how could a ...

  1. #1
    Registered User
    Join Date
    Jul 2002
    Posts
    34

    reversing strings

    Hi,
    I found this code in the source section of this web site. My question is this; how could a person cout the string entered in reverse? For example, if the user enters "der" the program should output "red" ? Thanks!
    Code:
    #include <iostream.h>
    
    int main()
    
    {
    
      char string[256];   //A nice long string
    
      cout<<"Please enter a long string: ";
    
      cin.getline(string, 256, '\n'); //The user input goes into string
    
      cout<<"Your long string was:"<<endl<<string;
    
      return 0;
    
    }

  2. #2
    Registered User
    Join Date
    Aug 2002
    Posts
    170
    strrev();
    Best Regards,

    Bonkey

  3. #3
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    One way is to use recursion.

    Code:
    #include <iostream>
    
    void printReverse(char* s) {
    	if (*s == '\0') return;
    	printReverse(s+1);
    	std::cout << *s;
    }
    
    int main() {
    	char buf[256];
    	std::cin.getline(buf, 256, '\n');
    	std::cout << buf << std::endl;
    	printReverse(buf);
    	std::cout << std::endl;
    }
    Another, perhaps easier way, would be to use a for loop that started from strlen(buf) and went down to 0, outputting the character at the index everytime... but that's not as fun to think about.

  4. #4
    Registered User
    Join Date
    Aug 2001
    Posts
    244
    create a temporary array and put the last character in the first slot of the array and then copy that array over to the original. use 2 for loops, one which increments and one which decrements

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    It's magic!
    Code:
    #include <iostream>
    #include <cstring>
    #include <algorithm>
    
    int main()
    {
      char a[] = "This is a test";
    
      std::cout<< a <<std::endl;
      std::reverse ( &a[0], &a[strlen ( a )] );
      std::cout<< a <<std::endl;
    
      return 0;
    }
    -Prelude
    My best code is written with the delete key.

  6. #6
    Registered User
    Join Date
    Jul 2002
    Posts
    34

    Smile

    Hey,
    Thanks all! Most of the code is way above me right now; I haven't gotten that far in my learn C++ in 21 days book. However, I do recognize the for loops! Could somebody show me an example using the two for loops?

    Hey Prelude or SilentStrike, what are the double colons?

  7. #7
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Hey Prelude or SilentStrike, what are the double colons?
    It's called a scope resolution operator. With the current standard of C++ there are things (very scientific term) called namespaces that group other things together. Everything defined by the C++ standard is in the namespace called std, so I used the scope resolution operator to get inside the namespace and retrieve the functions or objects that I wanted.

    cout<< a <<endl;

    This wouldn't work in the code I gave you because cout and endl are both enclosed in std and can't be accessed from outside of it. What this says is "look for cout in the global namespace" and "look for endl in the global namespace". Neither exist there, so it's an error. So I got inside std by doing this:

    std::cout<< a <<std::endl;

    It says "look for cout in namespace std " and "look for endl in namespace std". My appologies if I've confused you greatly.

    -Prelude
    My best code is written with the delete key.

  8. #8
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072
    Originally posted by Prelude

    std::reverse ( &a[0], &a[strlen ( a )] );
    Could be written as
    Code:
    std::reverse(a,a+strlen(a));
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

  9. #9
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    Code:
    #include <iostream>
    #include <cstring>
    using namespace std;
    int main()
    {
      char orig[80];
      cout << "enter a string of less than 80 char" << endl;
      cin.getline(orig, 79);
      int i;
      int length = strlen(orig);
      char copy[80];
      char temp;
      strcpy(copy, orig);
      for(i = 0; i < length/2; i++)
      {
         temp = copy[i];
         copy[i] = copy[length - 1 - i];
         copy[length - 1 - i] = temp;
      }
      cout << copy<< endl
      cout << orig << endl;
      return 0;
    }

  10. #10
    Registered User Nippashish's Avatar
    Join Date
    Sep 2002
    Posts
    34
    Code:
    #include <iostream>
    void rev(char);
    int main()
    {
    	char str[80];
    	std::cout << "Enter a string -> ";
    	std::cin.getline(str, 80);
    	rev(str);
    	std::cout << Your string has been reversed -> " << str;
    	return 0;
    }
    void rev(char * pstr)
    {
    	int len = 0;
    	char * pend = pstr;
    	while(*((++pend)+1) != '\0');
    	len = pend - pstr;
    	char cbeg,cend;
    	for (int i=0;i <= len/2;i++)
    	{
    		cbeg = *(pstr+i);
    		cend = *(pend-i);
    		*(pstr+i) = cend;
    		*(pend-i) = cbeg;
    	}
    }

  11. #11
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    I may just be a bit picky Nippashish, but that is way overcomplicating things. I'm curious to know why you wrote your reverse function that way.

    -Prelude
    My best code is written with the delete key.

  12. #12
    Registered User Nippashish's Avatar
    Join Date
    Sep 2002
    Posts
    34
    Originally posted by Prelude
    I may just be a bit picky Nippashish, but that is way overcomplicating things. I'm curious to know why you wrote your reverse function that way.

    -Prelude
    I didn't write it that way for any particular reason, I just wrote it and it that's how it turned out. I'm curious to know why you say it's so overcomplicated. (I don't doubt you, it's just I'd like to know what I'm missing).

  13. #13
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    Your code had several errors, but I'll ignore those for now.

    >I'm curious to know why you say it's so overcomplicated.
    Well, first I'll post a function that does the same thing, but you don't have to look twice to figure out how it works.
    Code:
    void rev ( char *pstr )
    {
      char temp;
      
      int end = strlen ( pstr ) - 1;
      
      for ( int i = 0; i < end; i++, end-- )
      {
        temp = pstr[i];
        pstr[i] = pstr[end];
        pstr[end] = temp;
      }
    }
    Very simple, start at the outer edges and swap the two items until the indices meet. It's easy to follow because it doesn't use pointers and pointer notation excessively and makes use of a common swapping idiom.

    >char * pend = pstr;
    >while(*((++pend)+1) != '\0');
    This is the first wacky syntax that could confuse a reader. While it may make perfect sense to you now, it will probably cause a double take for everyone else and even you later on because this isn't a commonly used idiom for finding the end of a string. Most people will use a function along the lines of strlen, but if you must write a loop to do this make it as understandable as possible and comment what you are trying to do:
    Code:
    // Find the end of the string
    while ( *pend != '\0' )
      ++pend;
    // Move back to the last valid character
    --pend;
    >len = pend - pstr;
    len really should be of the type ptrdiff_t instead of int, but this will usually work. Once again though, why perform the operation here? You could just as easily have counted characters In the above loop. You also don't need this variable since you already have a pointer to the first and last characters, these can be used to reverse the string without a length.

    >char cbeg,cend;
    You only need one temporary variable to use in a swap, any more and people may become confused at what you are trying to do.

    >cbeg = *(pstr+i);
    >cend = *(pend-i);
    >*(pstr+i) = cend;
    >*(pend-i) = cbeg;
    See the above paragraph, the common method for swapping two variables is

    put the first value in a temporary.
    put the second value in the first.
    put the temporary value in the second.

    So your use of uncommon idioms and techniques as well as pointers and pointer notation makes even this small function cause you to look twice. One of your goals should be to write code that is very simple and obvious, and comment constructs that aren't.

    -Prelude
    My best code is written with the delete key.

  14. #14
    Registered User
    Join Date
    Jul 2002
    Posts
    34
    Hi,
    Ok I think I'm getting closer but something is still not right. When I run this code it should reverse the code entered. It only reverses the first 2 characters. Where am I going wrong? Thanks!
    Code:
    #include<iostream.h>
    #include<string.h>
    
    int main()
    {
    	char orig[50],copy[50];
    	char temp;
    	int i,length;
    
    	cout<<"\nEnter string: "<< endl;
    	cin.getline(orig,49);
    	length = strlen(orig);
    	strcpy(copy,orig);
    
    	for(i=0;i<length;i++)
    	{
    		temp=copy[i];
    		copy[i]=copy[length-1-i];
    	}
    
    	cout<<copy<<endl;
    	return 0;
    }

  15. #15
    Registered User
    Join Date
    Oct 2002
    Posts
    1
    Originally posted by mcorn
    Hi,
    Ok I think I'm getting closer but something is still not right. When I run this code it should reverse the code entered. It only reverses the first 2 characters. Where am I going wrong? Thanks!
    Code:
    #include<iostream.h>
    #include<string.h>
    
    int main()
    {
    	char orig[50],copy[50];
    	char temp;
    	int i,length;
    
    	cout<<"\nEnter string: "<< endl;
    	cin.getline(orig,49);
    	length = strlen(orig);
    	strcpy(copy,orig);
    
    	for(i=0;i<length;i++)
    	{
    		temp=copy[i];
    		copy[i]=copy[length-1-i];
    	}
    
    	cout<<copy<<endl;
    	return 0;
    }
    the loop should appear like this ......

    for(i = 0; i < length/2; i++)
    {
    temp = copy[i];
    copy[i] = copy[length - 1 - i];
    copy[length - 1 - i] = temp;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Strings Program
    By limergal in forum C++ Programming
    Replies: 4
    Last Post: 12-02-2006, 03:24 PM
  2. Programming using strings
    By jlu0418 in forum C++ Programming
    Replies: 5
    Last Post: 11-26-2006, 08:07 PM
  3. Reversing Strings
    By Halo in forum C++ Programming
    Replies: 6
    Last Post: 03-18-2006, 03:58 PM
  4. Reversing strings using strtok()
    By Sure in forum C Programming
    Replies: 5
    Last Post: 06-27-2005, 06:33 PM
  5. Reading strings input by the user...
    By Cmuppet in forum C Programming
    Replies: 13
    Last Post: 07-21-2004, 07:37 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21