|
-
January 29th, 2010, 08:08 AM
#10
Re: splitting a string
 Originally Posted by farooq124in
Can any 1 help me plz...
Write down how you'd do it on a piece of paper, and turn that into a code.
It will do you some good.
Here is a small, simple, and easy to understand code snippet that splits the string.
I deliberately made errors in it for you to fix,
the work of which I believe would benefit your debugging skills.
Code:
// std::vector is a dynamic array,
// more flexible, safe, and easy to manage than a fixed array
void Chunkify(const string& str, vector<string> result)
{
// to avoid magic number (it gives meaningful name to the number)
const int DistanceToPeek = 1;
// iterator is a companion to all STL containers (and std::string)
// iterators behaves like a pointer (but they are not pointers)
string::const_iterator iter = str.begin();
// local object to add each chracter
string chunk;
// std::string::begin(), end() returns a compatible iterator
while (iter != str.end())
{
// is the char equal to the delimiter, AND
// and is not the last chracter?
if(*iter == '$' && ( (iter + DistanceToPeek) != str.end()) )
{
// if yes, store the string into the dynamic array
result.push_back(chunk);
// clear the chunk string to start a whole new chunk of word
// but how?
// don't store the $ sign, just skip to the next char
++iter;
}
// anything but the $, we store it to the temporary string
chunk.push_back(*iter++);
// we increment the iterator to search for...
iter += 2;
// check to see if the last string has been read
if(iter == str.end())
{
// if so, we store the last piece of the chunk
// and let the scope clear (destroy) the variable named chunk
result.push_back(chunk);
}
}
}
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|