我正在尝试用另一个字符(例如*
I'm trying to quickly replace multiple characters in a string with another character such as *
例如,我有一个字符串,例如:
For example, I have a string such as:
string = "abcdefghij"我还有一个索引向量,指示我要在上面的字符串中用另一个字符替换字母的位置.
I also have a vector of indexes that indicate where I would like to replace letters in the above string with another character.
string_indexes_replaced = c(1, 4, 6, 9)所需的输出:
"*bc*e*gh*j"我做了什么
我尝试了一种非常新手的方法,例如将字符分成列表,用*替换字符,然后将列表折叠回所需的字符串,如下所示:
I've tried a very novice like approach of splitting the characters up into a list, replacing the characters with *, then collapsing the list back into the desired string, as shown below:
library(dplyr) library(stringi) string%>% strsplit(split = "")%>% lapply(function(x) replace(x, string_indexes_replaced, rep("*", length(string_indexes_replaced))))%>% lapply(stri_flatten)%>% unlist(use.names = FALSE)输出
"*bc*e*gh*j"但是很明显,应该有比我上面发布的更简单,更快速的东西.有没有更简单的&比我在这里展示的要快?
but it is clear that there should be something simpler and faster than what I've posted above. Is there anything simpler & quicker than what I've demonstrated here?
推荐答案,除了 @ akrun ,您可以使用utf8ToInt()和intToUtf8制作
in base R, besides the method of substring() and for-loop shown by @akrun,, you can use utf8ToInt() and intToUtf8 to make it
v <- utf8ToInt(string) v[string_indexes_replaced ] <- utf8ToInt("*") res <- intToUtf8(v)给出
> res [1] "*bc*e*gh*j"更多推荐
通过索引快速替换字符串中的多个字符
发布评论