1 #include <Rcpp.h>
2 using namespace Rcpp;
3
str_count(std::string str,std::string sub,int start,int end)4 int str_count(std::string str, std::string sub, int start, int end) {
5 if(sub == "\0") {
6 return end - start + 2;
7 }
8
9 if(start > str.size()) {
10 return 0;
11 }
12
13 std::string str_ = str.substr(start, end - start + 1);
14
15 int count = 0;
16 size_t offset = str_.find(sub);
17
18 while (offset != std::string::npos) {
19 ++count;
20 offset = str_.find(sub, offset + sub.length());
21 }
22
23 return count;
24 }
25
26 // [[Rcpp::export]]
pystr_count_(CharacterVector strs,std::string sub,int start,int end)27 IntegerVector pystr_count_(CharacterVector strs, std::string sub, int start, int end) {
28 int input_size = strs.size();
29 IntegerVector output(input_size);
30
31 for(int i = 0; i < input_size; i++){
32 if(strs[i] == NA_STRING){
33 output[i] = NA_INTEGER;
34 } else {
35 output[i] = str_count(Rcpp::as<std::string>(strs[i]), sub, start, end);
36 }
37 }
38
39 return output;
40 }
41