Reversing a String

This is a discussion on Reversing a String within the C++ Programming forums, part of the General Programming Boards category; I'm trying to write a function that will return the reverse of a character array or string. Here's how I ...

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    9

    Reversing a String

    I'm trying to write a function that will return the reverse of a character array or string. Here's how I want everything to work out:

    1). The user is asked for a string/character array.
    2). The user enters a string/character array (the size is unknown until the user enters the string/character array, so I'm not sure how to set up the memory allocation).
    3). The function reads the string/character array and reverses it. So if the user enters, "this is my test" the function will return "tset ym si siht".

    I can't figure out any way to do this other than to create a string or character array and copy one letter at a time from the user input into the reversed string/character array. Unfortunately, I can't seem to figure out how to copy a single character from one string into another.

    Here's the code I have so far:

    ******************************************

    string ReverseString(string input){

    int length = input.length();

    string rString = "\0";

    for(int i = 0; i<length; i++)
    // CODE HERE THAT WILL
    // COPY ONE CHARACTER FROM
    // INPUT INTO rString

    return rString;

    }

    ******************************************

    Thanks in advance!

  2. #2
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    If you want to add to a string all you have to do is use the += operator eg

    string name = "z";
    name +="e";
    name +="n";

  3. #3
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    // swaps given two characters
    void swap(char& a, char& b) {
        char temp = a;
        a = b;
        b = temp;
    }
    
    /* reverses string by swapping first character with last character
     * second character with second to last character, third character with
     * third to last character, etc.  
     */
    string reverse(string source) {
         int len = source.length();
         int count;
         
         for (count = 0; count < len/2; count++) {
             swap(source[count], source[len-count-1]);
         }
         return source;
    }
    
    /* tests string reversal by outputting string before reversing it,
     * reversing the string and outputting the reversed string, and then 
     * reversing it again to see if the twice reversed string is the same as 
     * the original 
     */
    bool test(string& testString) {
         string copy = reverse(testString);
         cout << "String before reversing: " << testString<< "\n";     
         cout << "String after reversing : " << copy << "\n";
         
         copy = reverse(copy);
         
         if ( copy == testString) {
            cout << "It may have worked" << endl;
            return true;
         }
         else {
              cout << "It did not work" << endl;
              return false;
         }
    }
    
    // calls test for an array of strings
    int main(int argc, char *argv[])
    {
        string testStringArray[] = {"Rob", "Words", "SilentStrikeIsHelpingYouOut",
         "radar", "five"};
         
         // ugly way of finding out how many strings are in array, but will work if 
         // more strings are added to the array
        int arrayLen = sizeof testStringArray / sizeof testStringArray[0];  
        
        int count;
        for (count = 0; count < arrayLen; count++) {
            test(testStringArray[count]);
        }
        
        char wait; cin >> wait;
      return 0;
    }
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  4. #4
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    Gah... those code tags don't seem to work.
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  5. #5
    Registered User
    Join Date
    Aug 2001
    Posts
    403
    If you made this a vector you could easily avoid this


    Originally posted by SilentStrike

    If you made this a vector you could easily avoid this

    // ugly way of finding out how many strings are in array, but will work if
    // more strings are added to the array
    int arrayLen = sizeof testStringArray / sizeof testStringArray[0];


    [/B]

  6. #6
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    That is a specific instance in which the easy method to define all the data in the array is worth the lack of all features of a vector.
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  7. #7
    Registered User
    Join Date
    Aug 2001
    Posts
    403

    it's also not a sensitive operation

    his code isnt so critical that he needs to use an array either, i just prefer vectors because if i ever need to use an algorithm on them it's already compatible.


    anyway i just remembered there is a reverse algorithm defined by the STL.. i can't find how it works right now though so i don't know if it'd be useful

  8. #8
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    I prefer usually vectors as well.. but that was a rare case in which I think it's better to just use an array.

    string testStringArray[] = {"Rob", "Words", "SilentStrikeIsHelpingYouOut",
    "radar", "five"};

    int arrayLen = sizeof testStringArray / sizeof testStringArray[0];

    is more readable than

    vector<string> testStringArray;
    testStringArray.push_back("Rob");
    testStringArray.push_back("Words");
    testStringArray.push_back("SilentStrikeIsHelpingYo uOut");
    testStringArray.push_back("radar");
    testStringArray.push_back("five");

    int arrayLen = testStringArray.size();
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  9. #9
    Registered User
    Join Date
    Aug 2001
    Posts
    403

    true

    true, i'm just trying to open some peoples eyes to vectors.

  10. #10
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007

    <algorithm>

    >>anyway i just remembered there is a reverse algorithm defined by the STL.. i can't find how it works right now though so i don't know if it'd >>be useful


    Like this -


    #include <iostream>
    #include <string>
    #include <algorithm>

    using namespace std;

    int main ()
    {
    string name = "zen";

    string::iterator start=name.begin();
    string::iterator end=name.end();

    reverse(start,end);

    cout << name<<endl;

    return 0;

    }

  11. #11
    Unregistered
    Guest
    #include<iostream.h>
    #include<string.h>

    void main()
    {
    char ass[255];

    cin.getline(ass, 255, '\n');
    cout<<"String before reverse: "<< ass<<"\n";
    strrev(ass);
    cout<<"String after reverse: "<<ass<<"\n";
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 02:02 AM
  2. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 04:58 PM
  3. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 01:56 PM
  4. problems with overloaded '+' again
    By Brain Cell in forum C++ Programming
    Replies: 9
    Last Post: 04-14-2005, 06:13 PM
  5. Again Character Count, Word Count and String Search
    By client in forum C Programming
    Replies: 2
    Last Post: 05-09-2002, 12:40 PM

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