0

我正在用 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”替换任何不允许的字符,那也是可取的。

4

3 回答 3

3

您可以使用 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" 
于 2021-04-12T19:33:10.083 回答
3

这是一种使用str_replace_all. 我们可以生成一个正则表达式来识别不在集合中的字符。例如,[^AC]匹配任何不匹配的字符AC

library(stringr)
StringtoConvert="ABC"
strAllowedChars="AC"
str_replace_all(StringtoConvert,paste0("[^",strAllowedChars,"]"),"G")
#[1] "AGC"

set.seed(12345)
sample(LETTERS,50,replace = TRUE) %>% paste(collapse = "") -> StringtoConvert2
str_replace_all(StringtoConvert2,paste0("[^",strAllowedChars,"]"),"G")
#[1] "GGGGGGGGGGGGGGGGGGAGGGGGCGGGGGGGGGGGGGGGGGGGGGGGGG"
于 2021-04-12T21:21:19.570 回答
0

仅使用 R Base:

StringtoConvert="ABC"
strAllowedChars="AC"
Res=nchar(StringtoConvert)-sum(strsplit(StringtoConvert,"")[[1]] %in% strsplit(strAllowedChars,"")[[1]])
于 2021-12-21T14:39:25.200 回答