title: Slice a string at consecutive indices with R / Rcpp?
body: <p>I want to write a function that slices a 'string' into a vector, sequentially, at a given index. I have a fairly adequate R solution for it; however, I figure that writing the code in C/C++ would likely be faster. For example, I'd like to be able to write a function 'strslice' that operates as follows:</p>
  
  <pre><code>x &lt;- "abcdef"
  strslice( x, 2 ) ## should return c("ab", "cd", "ef")
  </code></pre>
  
  <p>However, I'm not sure how to handle treating elements of the 'CharacterVector' passed around in the Rcpp code as strings. This is what I imagine might work (given my lack of C++/Rcpp knowledge I'm sure there's a better approach):</p>
  
  <pre><code>f &lt;- rcpp( signature(x="character", n="integer"), '
    std::string myString = Rcpp::as&lt;std::string&gt;(x);
    int cutpoint = Rcpp::as&lt;int&gt;(n);
    vector&lt;std::string&gt; outString;
    int len = myString.length();
    for( int i=0; i&lt;len/n; i=i+n ) {
      outString.push_back( myString.substr(i,i+n-1 ) );
      myString = myString.substr(i+n, len-i*n);
    }
    return Rcpp::wrap&lt;Rcpp::CharacterVector&gt;( outString );
    ')
  </code></pre>
  
  <p>For the record, the corresponding R code I have is:</p>
  
  <pre><code>strslice &lt;- function(x, n) {
    x &lt;- as.data.frame( stringsAsFactors=FALSE, 
                        matrix( unlist( strsplit( x, "" ) ), ncol=n, byrow=T )
    )
  
    do.call( function(...) { paste(..., sep="") }, x )
  
  }
  </code></pre>
  
  <p>...but I figure jumping around between data structures so much will slow things down with very large strings.</p>
  
  <p>(Alternatively: is there a way to coerce 'strsplit' into behaving as I want?)</p>