Note that there are some explanatory texts on larger screens.

plurals
  1. POSplitting a string with delimiter in C++
    primarykey
    data
    text
    <p>There are a few examples about this question. However most of the answers are not what I am looking for.</p> <p>I am looking for a way to implement an efficient and easy function rather than using boost or any other non STL libraries. If you ask me why, in most coding competitions and interviews, you are not allowed to use them.</p> <p>Here is the closest that I can approach:</p> <pre><code>vector&lt;string&gt; SplitString(const char *str, char c) { vector&lt;string&gt; result; do { const char *begin = str; while(*str != c &amp;&amp; *str) { str++; } result.push_back(string(begin, str)); } while (0 != *str++); return result; } int main() { string mainString = "This is a sentence. Another sentence. The third sentence. This is the last sentence."; vector&lt;string&gt; sentences; sentences = SplitString(mainString.c_str(), '.'); while (!sentences.empty()) { cout &lt;&lt; sentences.back() &lt;&lt; endl; sentences.pop_back(); } return 0; } </code></pre> <p>Now the problem with this is, it can only have a char delimiter not string. I have thought of implementing a few ways but they seemed way too complex. The easiest one that I thought was, convert delimiter to char array use <code>c</code> as the first char of the delimiter char array after this:</p> <pre><code>while(*str != c &amp;&amp; *str) { str++; } const char *beginDelim = *cArr; while(1) { if (*str == *cArr &amp;&amp; *str &amp;&amp; *cArr) { str++; cArr++; } else if (!*cArr) { break; } else if (*cArr) { cArr = beginDelim; } } </code></pre> <p>And the code continues from <code>result.push_back()</code> part.</p> <p>So I was wondering if are there any way to implement an efficient and easy function for splitting a string with a string delimiter?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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