Rcpp 函数中的 nul 字节字符
nul byte character in Rcpp function
我正在寻找一种比较短字符串重叠的方法。
我想我可能会找到一个合理的方法,使用 stringdist
包使用 lcs
方法,但它似乎在做一些不同的事情。
这个 C 标记的 Whosebug 问题的公认答案:
Detecting length of overlap between two strings
int overlap(const char *s1, const char *s2){
int i = 0;
while (*s1 != '[=10=]' && *s2 != '[=10=]') {
if (*s1++ == *s2++) i++;
}
return i;
}
涉及使用nul字节字符表示空字符串。
我怎样才能将其转化为适用于 Rcpp 的内容?当我尝试将其包装在 cppFunction
中时,我收到一条错误消息,指出不允许使用此字符。
这是因为当你使用cppFunction
定义你的C++函数时,你需要转义\
,即如果你想在C++代码中有[=15=]
,你需要在给cppFunction
的字符串中写\0
:
Rcpp::cppFunction( "
int overlap(const char* s1, const char* s2){
int i = 0;
while (*s1 != '\0' && *s2 != '\0') {
if (*s1++ == *s2++) i++;
}
return i;
}")
这给你:
> overlap( "foo", "foooo")
[1] 3
请注意,如果您将函数放在 .cpp 文件中,则不需要它,这是推荐的做法:
#include <Rcpp.h>
using namespace Rcpp ;
// [[Rcpp::export]]
int overlap(const char* s1, const char* s2 ){
int i = 0;
while (*s1 != '[=12=]' && *s2 != '[=12=]') {
if (*s1++ == *s2++) i++;
}
return i;
}
我正在寻找一种比较短字符串重叠的方法。
我想我可能会找到一个合理的方法,使用 stringdist
包使用 lcs
方法,但它似乎在做一些不同的事情。
这个 C 标记的 Whosebug 问题的公认答案:
Detecting length of overlap between two strings
int overlap(const char *s1, const char *s2){
int i = 0;
while (*s1 != '[=10=]' && *s2 != '[=10=]') {
if (*s1++ == *s2++) i++;
}
return i;
}
涉及使用nul字节字符表示空字符串。
我怎样才能将其转化为适用于 Rcpp 的内容?当我尝试将其包装在 cppFunction
中时,我收到一条错误消息,指出不允许使用此字符。
这是因为当你使用cppFunction
定义你的C++函数时,你需要转义\
,即如果你想在C++代码中有[=15=]
,你需要在给cppFunction
的字符串中写\0
:
Rcpp::cppFunction( "
int overlap(const char* s1, const char* s2){
int i = 0;
while (*s1 != '\0' && *s2 != '\0') {
if (*s1++ == *s2++) i++;
}
return i;
}")
这给你:
> overlap( "foo", "foooo")
[1] 3
请注意,如果您将函数放在 .cpp 文件中,则不需要它,这是推荐的做法:
#include <Rcpp.h>
using namespace Rcpp ;
// [[Rcpp::export]]
int overlap(const char* s1, const char* s2 ){
int i = 0;
while (*s1 != '[=12=]' && *s2 != '[=12=]') {
if (*s1++ == *s2++) i++;
}
return i;
}