Here's what I think you should do. Don't worry for now about why/how the code did what it did (obviously, you can and probably should go over it later and figure out what it does and why for your own personal knowlege). Test it out with all sorts of input and make sure it does what it's supposed to (break strings into "all non-punctuation" and "all punctuation" strings). If it does work for all possible test cases, go to the next step.
while (pos != string::npos)
{
string::size_type end = str.find_first_of(punct, pos);
if (end == pos) end = str.find_first_not_of(punct, pos);
vec.push_back(str.substr(pos, end - pos));
pos = end;
}
Break line 7 into two lines:
string newString = str.substr (pos, end - pos);
vec.push_back (newString);
So you end up with this:
while (pos != string::npos)
{
string::size_type end = str.find_first_of(punct, pos);
if (end == pos) end = str.find_first_not_of(punct, pos);
string newString = str.substr (pos, end - pos);
vec.push_back (newString);
pos = end;
}
Now, if newString contains punctuation, you need to change it into one string for every character. If it doesn't, push the whole string as you do in line 8 above. Test whether it has any punctuation in it, as before, and act accordingly (push it onto the vector if it's all non-punctuation, split it further if it is punctuation):
if (newString.find_first_of (punct) == string::npos)
{
// newString doesn't contain punctuation. Push it.
vec.push_back (newString);
}
else
{
// newString is punctuation. Break newString into one-character strings and push each of them onto vec.
}
So your job is:
- Try Tom Gunn's code out. Make sure it "works" for all possible test cases (i.e. change line 11 below for every possible test case you can think of and make sure the code "behaves". I imagine it does. Tom Gunn's code generally does.
. But you need to verify that.
- If it does, look at my revised code below. Run it. See what it does. now delete my line 31. Change line 30 so it does what you need it to do, which is to take a string like "****))" strored in
newString and break it into six separate strings, and push them all onto the vec vector
#include <iostream>
#include <string>
#include <vector>
int main()
{
using namespace std;
string const punct = "+-*/<=!>{()};,";
string str = "dressed(to**!impress{{)";
string::size_type pos = 0;
vector<string> vec;
while (pos != string::npos)
{
string::size_type end = str.find_first_of(punct, pos);
if (end == pos) end = str.find_first_not_of(punct, pos);
string newString = str.substr (pos, end - pos);
if (newString.find_first_of (punct) == string::npos)
{
// newString doesn't contain punctuation. Push it.
vec.push_back (newString);
}
else
{
// newString is punctuation. Break newString into one-character strings and push each of them onto vec.
vec.push_back ("PUNCTUATION");
}
pos = end;
}
for (int a = 0; a < vec.size(); ++a)
{
cout << "vector " << a << ": " << vec.at(a) << '\n';
}
return 0;
}