remo-6ren">
gpt4 book ai didi

从字符串中删除第 n 个空格

转载 作者:行者123 更新时间:2023-12-05 01:05:18 25 4
gpt4 key购买 nike

我需要从字符串中删除第 n 个空格。

例如,我想在这里删除第一个空格 my_string <- "this is a string"就是现在这样:

"thisis a string"

但我还需要能够从原始文本中删除第二个空格,以便生成:

"this isa string"

我该怎么做?

最佳答案

这个函数根据""分割字符串,将分割字符串的第nn+1的元素粘贴在一起,然后然后将字符串的其余部分粘贴在一起,不包含拆分字符串的 n+1 元素。

remove_n_ws = function(n, my_string) {  
sub_str = unlist(strsplit(my_string, " "))
sub_str[n] = paste(sub_str[n], sub_str[n+1], sep="")
paste(sub_str[-c(n+1)], collapse=" ")
}
> remove_n_ws(1, my_string)
[1] "thisis a string"
> remove_n_ws(2, my_string)
[1] "this isa string"
> remove_n_ws(3, my_string)
[1] "this is astring"

关于从字符串中删除第 n 个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70713650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com