Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Single Delimiter:</strong></p> <p>You wrote much too much code to do this. You can do it in a few lines. You are getting <em>very</em> over complicated. And there's no reason to really do anything with pointers for this.</p> <pre><code>vector&lt;string&gt; Split(string s, char delim) { vector&lt;string&gt; strings; for(istringstream ss(s); getline(ss, s, delim); strings.push_back(move(s))); return strings; } </code></pre> <p><strong>Multiple Delimiters:</strong></p> <p>A solution for using multiple delimiters is more complicated. You can no longer leverage off of <code>getline</code>, which means you're basically writing part of <code>getline</code>'s functionality yourself. But still, it can be quite short.</p> <pre><code>vector&lt;string&gt; Split(const string&amp; s, const char* delims) { vector&lt;string&gt; strings; for(string::size_type start = 0, end; end != string::npos &amp;&amp; start &lt; s.size(); start = end+1) { end = s.find_first_of(delims, start); strings.push_back(s.substr(start, end-start)); } return strings; } </code></pre> <p>This will add blank strings when delimiters are next to each-other. If that's not the desired behavior for adjacent delimiters, this can be easily avoided by guarding the <code>push_back</code> with <code>if(start != end)</code>.</p> <p><strong>Conclusion:</strong></p> <p>When you are starting to write a low level algorithm like this, pseudo code it out in broad terms and then before writing any code check what the C++ standard library can provide to cut out parts or all of your work. You'll end up with smaller, less error prone, and more understandable code. No one wants to see a hand rolled implementation for <code>find_first_of</code>, for example. It's much more clear to read the words <code>find_first_of</code>. It's clear what that function is going to do, and that it's bug free (hopefully).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload