[Rcpp-devel] Bug report: String::replace_first() and String::replace_last()

Masaki Tsuda teuder at gmail.com
Sat May 14 15:36:46 CEST 2016


Hello, all

This is my first post to this mailing list.

I might have found bugs with String::replace_first() and
 String::replace_last().
The bugs can be reproduced by following code.
(R version 3.2.3  Rcpp 0.12.4)

-------------------
// [[Rcpp::export]]
void rcpp_string(){

    String s("AABCDABCDA");
    Rcout << "replace_all()\n";
    Rcout << s.replace_all("AB", "ab").get_cstring()  << "\n";
    Rcout << "\n";

    s="AABCDABCDA";
    Rcout << "replace_first()\n";
    Rcout << s.replace_first("AB", "ab").get_cstring() << "\n";
    Rcout << "\n";

    s="AABCDABCDA";
    Rcout << "replace_last()\n";
    Rcout << s.replace_last("AB", "ab").get_cstring()  << "\n";
    Rcout << "\n";

}
-------------------
> rcpp_string()
replace_all()
AabCDabCDA

replace_first()
abBCDABCDA

replace_last()
AABCDABCDab
-------------------

The problem is caused by find_first_of() and find_last_of() and it can be
resolved by replacing these functions by find() and rfind().

-------------------
inline String& replace_first(const char* s, const char* news) {
    RCPP_STRING_DEBUG_2("String::replace_first(const char* = '%s' , const
char* = '%s')", s, news);
    if (is_na()) return *this;
    setBuffer();
    size_t index = buffer.find(s);
    //size_t index = buffer.find_first_of(s);
    if (index != std::string::npos) buffer.replace(index, strlen(s), news);
    valid = false;
    return *this;
}

inline String& replace_last(const char* s, const char* news) {
    RCPP_STRING_DEBUG_2("String::replace_last(const char* = '%s' , const
char* = '%s')", s, news);
    if (is_na()) return *this;
    setBuffer();
    size_t index = buffer.rfind(s);
    //size_t index = buffer.find_last_of(s);
    if (index != std::string::npos) buffer.replace(index, strlen(s), news);
    valid = false;
    return *this;
}
-------------------
> rcpp_string()
replace_all()
AabCDabCDA

replace_first()
AabCDABCDA

replace_last()
AABCDabCDA
-------------------

Regards

-------------------------------------------------------------------

     Masaki Tsuda
     E-mail : teuder at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20160514/3b748c15/attachment-0001.html>


More information about the Rcpp-devel mailing list