-1

I have a std::string that contains a random phrase.

For example:

std::string str{ "Lorem ipsum" };

I'd like to take that string and convert it into a std::vector<std::vector<char>> (each sub-array would have all the characters for one word in the phrase, i.e. splitting on spaces).

For example after the conversion:

std::vector<std::vector<char>> arr{ { 'L', 'o', 'r', 'e', 'm' }, { 'i', 'p', 's', 'u', 'm' } };

Furthermore, I'd like to then be able to convert the std::vector<std::vector<char>> back into a std::string.

Thank you for the help!

Jasper1378
  • 35
  • 5
  • 3
    Start with a smaller problem: How would you split the string on spaces? – user4581301 Mar 19 '22 at 15:17
  • 1
    Please read: [How do I iterate over the words of a string?](https://stackoverflow.com/questions/236129/how-do-i-iterate-over-the-words-of-a-string). You can then use iterators to convert strings to vector (AFAIR there is also plenty of existing question/answers like this on S.O.). – Jérôme Richard Mar 19 '22 at 15:19
  • 2
    More straightforward to use a `vector>. You can still subscript each char like `v[i][j]`. – doug Mar 19 '22 at 15:46

1 Answers1

-1
#include <bits/stdc++.h>
using namespace std;


int main()
{
    vector<vector<char>> v;
    vector<char> c;
    string s = "hello world this";
    for(int i=0;i<s.size();i++)
    {
        
        if(s[i]==' ')
        {
            v.push_back(c);
            c.clear();
        }else{
            c.push_back(s[i]);
        }
    }
    for(int i =0;i<v.size();i++)
    {
        for(int j=0;j<v[i].size();j++)
        {
            cout<<v[i][j];
        }
        cout<<endl;
    }
    return 0;
}
Pushpraj Singh
  • 107
  • 1
  • 10
  • 1
    Minor correction for future viewers. The last word doesn't get put in `v` because the string doesn't finish with a space. To fix: add the lines `v.push_back(c);` and `c.clear();` outside of the first `for` loop. – Jasper1378 Mar 19 '22 at 16:47
  • This is a code-only answer. Code-only answers have an annoying tendency to produce [Cargo Cult Programmers](https://en.wikipedia.org/wiki/Cargo_cult_programming). You can salvage this by explaining why the code does and why. Also consider using descriptive variable names and removing well-known problem-causers like `using namespace std;` and non-standard headers like `#include `. – user4581301 Mar 19 '22 at 17:16