r - R中是否有相当于vb.net的instr
问题描述
我正在用 R 重写我的 vb.net 代码并且遇到了障碍。vb.net 中的代码本质上是计算字符串中未出现在允许字符的字符串中的字符数。vb.net 中的代码是:
StringtoConvert="ABC"
strAllowedChars="AC"
For i= 1 to len(StringtoConvert)
If InStr(1, strAllowedChars, StringtoConvert(i))=0 then
disallowed=disallowed+1
Else
End If
Next
我可以看到如何在 R 中使用循环来搜索字符串中每个允许的字符,但是在 R 中有没有办法使用像上面的 strAllowedChars 这样的聚合来做到这一点?
R 中 stringr 包的 str_count 函数是我发现的最接近的,但它看起来与整个 strAllowedChars 匹配,而不是独立查看每个字符。如何测试 StringtoConvert 以确保它仅包含 strAllowedChars 作为单个字符。换句话说,在上面的示例中,如果 StringtoConvert 中的字符与 strAllowedCharacters 中的字符之一不匹配,那么我需要将其标识为这样并使用另一个调用来替换它或直接替换它。
我尝试过的 R 代码是:
library(stringr)
testerstring<-"CYA"
testpattern<-"CA"
newtesterstring<-str_count(testerstring,testpattern)
print(newtesterstring)
所需的输出是 StringtoConvert 中基于允许的字符 strAllowedChars 被禁止的字符数。然后,我将在循环中使用它,使用 if then 语句将任何不允许的字符更改为“G”,因此如果我可以跳过计数步骤,而只是用“G”替换任何不允许的字符,那也是可取的。
解决方案
您可以使用 strsplit 获取 strAllowedChars 中的每个字符,然后从 StringtoConvert 中的字符总数中减去 StringtoConvert 中允许的字符数。
如果这就是您所追求的,那将为您提供 StringtoConvert 中不允许使用的字符的总数。
StringtoConvert <- "ABCrrrrr"
strAllowedChars <- "ACT"
disallowed <- nchar(StringtoConvert) - sum(stringr::str_count(StringtoConvert, strsplit(strAllowedChars,"")[[1]]))
disallowed
要用“G”替换所有允许的字符,你可以试试这个。
> StringtoConvert <- "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
> strAllowedChars <- "ACT"
>
> stringr::str_replace_all(StringtoConvert, paste0("[^", strAllowedChars, "]"), "G")
[1] "AGCGGGGGGGGGGGGGGGGTGGGGGG"
推荐阅读
- java - Java <-> Angular Dto
- javascript - 使用 node.js 从 Spring Boot 2 响应中读取传入的 HTTPS 标头
- javascript - 如何在 PHP laravel 或 Java Script 中比较 3 个不同的数组
- javascript - 在 Javascript 中为几乎相同的输入获取不同的 typeof
- c++ - 如何在 C++ 中为 copy_if 等定义“一元谓词”?
- scala - 错误:未知参数“idea-shell”
- c# - 如何使用 serialPort DatatReceived 事件更改 tabControl 中的活动选项卡?
- asp.net - 将点击事件添加到日历内的动态按钮
- ruby-on-rails - Rails - 茧/简单表单嵌套字段未显示
- java - 对话流 startListening()