删除某些字符后的字符串数组中的所有内容

这个相当简单的朱莉娅问题使我有些困惑。

假设我有一个格式为“ xxx_xxx”的字符串数组。是否有一个将从“ _”开始删除所有内容的函数?

names = ["last1_first1","last2_first2"]

是否有一个简单的函数会返回

["last1","last2"]
评论
  • Mcu〢
    Mcu〢 回复

    You are looking for split:

    julia> names  = ["last1_first1", "last2_first2"]
    2-element Array{String,1}:
     "last1_first1"
     "last2_first2"
    
    julia> split.(names, "_")
    2-element Array{Array{SubString{String},1},1}:
     ["last1", "first1"]
     ["last2", "first2"]
    

    Note that I am using the dot broadcasting syntax split.() here to apply the split function elementwise to the array of names.

  • punde
    punde 回复

    我只是有一些语法问题

    names[:] = map((x) -> replace(x,r"_.*",""),names[:])