reversing a string

Can someone provide feedback on my reverse function and how it can be made better? Or more correct?

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <string>

using namespace std;

void reverse(string &str)
{
    string temp;

    int pos = str.length()-1;

    for(int i = str.length()-1; i >= 0; i--)
    {
        if(str[i] == ' ' || i == 0)
        {
            if(i == 0)
            {
                --i;
            }
            for(int j = i+1; j <= pos; j++)
            {
                temp += str[j];
            }
            temp+= ' ';
            pos = i-1;
        }
    }
    str = temp;

}


int main()
{
    string r = "hello world hi there";

    reverse(r);

    cout << r;
}
Hello

1
2
3
4

std::string in("hello world");
std::string out(in.rbegin(), in.rend());


same logic, if you want to reverse the word ; you split on space ; then reverse your std::vector, then join back; done, this is a c++ forum.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// courtesy of me-self
template <typename StrT, typename ArrayT>
void tokenizer(const StrT & in, ArrayT & tokens, const StrT & delimiter, bool trim = false)
{
// for sanity you should have ArrayT::value_type ==  StrT just 
// allowing std::set/list here 

   using str_size_type = typename StrT::size_type;
   using value_type = typename ArrayT::value_type;
   using size_type = typename ArrayT::size_type;

   str_size_type pos, last_pos = 0;

   while (true) {
      pos = in.find_first_of(delimiter, last_pos);
      if (pos == std::string::npos) {
         pos = in.length();
         if (pos != last_pos || !trim) {
            tokens.push_back(
                  value_type(in.data() + 
                  last_pos, static_cast<size_type>(pos) - last_pos )
            );
         }
         break;
      } else {
         if (pos != last_pos || !trim) {
            tokens.push_back(
                  value_type(in.data() + 
                  last_pos, static_cast<size_type>(pos) - last_pos )
            );
         }
      }
      last_pos = pos + 1;
   }
}


sorry for the edits ; I am writing that thing live.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
std::vector<std::string> split(const std::string & in, char c = 0x20)
{
   std::vector<std::string> result;
   const char * p = in.c_str();
   while (0 != *p) {
      const char * q = p;
      while(*p != c && *p) { p++; }
      result.push_back(std::string(q, p));
      p++;
   }
   return result;
   // further digging-in using a double linked iterator and mov'g-in-place
  // ....char * p = in;
 // ....char * q = p + size;
// for(--q;  ... ; ++p, --q)
}

std::string join(const std::vector<std::string> & in, char c = 0x20)
{
   std::string buf;
   for (std::vector<std::string>::const_iterator it = in.begin() ; it != in.end() ; ++it) {
      buf += *it; if (std::distance(it, in.end()) > 1) { buf += c; }
   }
   return buf;
}

std::string reverse(const std::string & in)
{
   std::vector<std::string> toks = split(in);
   std::reverse(toks.begin(), toks.end());
   return join(toks);
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14

#include <iostream>
#include <vector>
#include <string>

...

int main(int argc, const char * argv[])
{
   std::string in(u8"héllo world hi thére");
   std::cout << "'" << reverse(in) << "'" << std::endl;
   return 0;
}
Last edited on
So you did what I did using a vector?
mostly, I do what I can
Last edited on
Thanks for that implementation mmw.
If you're talking about reversing a sequence of words (no punctuation to worry about) then the standard way is to do it (in-place) is:
- reverse the entire string
- reverse the letters of each individual word

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <string>
#include <algorithm>

// reverse the order of a string of words (does not deal with
// punctuation is a meaningful way but does handle spaces.)
void reverse_words(std::string& sentence) {
    static const char whitespace[] = " \t";
    std::string::iterator i_beg = sentence.begin();
    std::string::iterator i_end = sentence.end();
    // reverse the whole string
    std::reverse(i_beg, i_end);
    // find the start of the first word
    std::string::size_type from = sentence.find_first_not_of(whitespace);
    std::string::size_type to   = sentence.npos;
    do {
        // find the end of the next word
        to = sentence.find_first_of(whitespace, from);
        // and reverse it, handling the fact that it might be the last word
        // with no trailing spaces or have trailing space
        if(to != sentence.npos) {
            std::reverse(i_beg + from, i_beg + to);
            // look for the start of the next word
            from = sentence.find_first_not_of(whitespace, to);
        } else {
            // run out of string
            std::reverse(i_beg + from, i_end);
            from = sentence.npos;
        }
    }
    while(from != sentence.npos);
}

// test function
void test_reverse_words(const std::string& sentence) {
    std::cout << "sentence:\n";
    std::cout << "\"" << sentence << "\"\n";

    std::string reversed_sentence = sentence;
    reverse_words(reversed_sentence);
    std::cout << "reversed sentence:\n";
    std::cout << "\"" << reversed_sentence << "\"\n";

    std::cout << "\n";
}

int main() {
    // try a few different strings
    test_reverse_words("an example sentence");
    test_reverse_words(" another  example   sentence    ");
    test_reverse_words("one");
    test_reverse_words("    ");
    test_reverse_words("");

    return 0;
}


C++ Shell output:

sentence:
"an example sentence"
reversed sentence:
"sentence example an"

sentence:
" another  example   sentence    "
reversed sentence:
"    sentence   example  another "

sentence:
"one"
reversed sentence:
"one"

sentence:
"    "
reversed sentence:
"    "

sentence:
""
reversed sentence:
"" 



Andy

Reverse the ordering of words in a string
http://stackoverflow.com/questions/1009160/reverse-the-ordering-of-words-in-a-string
Last edited on
Topic archived. No new replies allowed.