Arrays 向量字符串替换为Julia

Arrays 向量字符串替换为Julia,arrays,string,julia,Arrays,String,Julia,我想找到x中包含“x”的元素,并将“x”替换为“” A对循环使用,我可以: for i=1:length(x) x[i] = replace(x[i], "X", "") end 这就是Julia中字符串向量操作的方式吗?或者是否有一组我应该使用的函数集.replace或apply(如R中所用的sapply(x,replace,“x”,”))呢?您可以这样做 [replace(i,"X","") for i in x] 但正如Stefan在评论中指出的那样,它创建了一个新的向量。 正

我想找到
x
中包含
“x”
的元素,并将
“x”
替换为“”

A对循环使用
,我可以:

for i=1:length(x)
  x[i] = replace(x[i], "X", "")
  end
这就是Julia中字符串向量操作的方式吗?或者是否有一组我应该使用的函数集
.replace
apply
如R中所用的sapply(x,replace,“x”,”)
)呢?

您可以这样做

[replace(i,"X","") for i in x]
但正如Stefan在评论中指出的那样,它创建了一个新的向量。 正确的方法应该是(如马特所解释的)

为了快速回顾一下replace函数,下面是Julia官方文档中的内容

help?> replace
search: replace redisplay

  replace(string, pat, r[, n])

  Search for the given pattern pat, and replace each occurrence with r. If n is provided, replace at most n occurrences. As
  with search, the second argument may be a single character, a vector or a set of characters, a string, or a regular
  expression. If r is a function, each occurrence is replaced with r(s) where s is the matched substring. If pat is a
  regular expression and r is a SubstitutionString, then capture group references in r are replaced with the corresponding
  matched text.

julia>

使用for循环或理解是一个很好的解决方案,通常是一个性能非常好的解决方案。Julia中的循环速度很快,所以您不必担心仅仅为了使代码快速而对代码进行矢量化。也就是说,在即将发布的0.6版本中,您可以在Julia中编写快速矢量化代码,因为字符串现在在广播中被视为标量元素:

julia> replace.(x, "X", "")
100-element Array{String,1}:
 "lod"
 "kk"
 "eco"
 "jac"
 ⋮
 "ojn"
 "hmc"
 "pb"
您可以通过以下方式就地完成:

x .= replace.(x, "X", "")

这可以产生一个带有替换的新向量,但它不会在适当的位置修改字符串
x
的向量。哦,是的,@StefanKarpinski。谢谢,这是个好办法。你可以使用
map更简洁一点:
map!(s->replace(s,“X”,“X”,X,X)
请记住,范围也适用于字符:
'a':'z'
是有效的范围,
字符串。('a':'z')
生成字符串向量。在您的特定情况下,由于“X”,您需要执行额外的步骤:
v=string。(['a':'p';'X'])
。无论如何,我认为这比把所有的字母都打出来更方便。
julia> replace.(x, "X", "")
100-element Array{String,1}:
 "lod"
 "kk"
 "eco"
 "jac"
 ⋮
 "ojn"
 "hmc"
 "pb"
x .= replace.(x, "X", "")