【问题标题】:String splitting before character字符前的字符串拆分
【发布时间】:2019-08-08 06:34:27
【问题描述】:

我是新手,一直在使用 split 来发挥我的优势。最近我遇到了一个问题,我想拆分一些东西,并将拆分字符保留在我的第二个切片中而不是删除它,或者像使用 SplitAfter 一样将它留在第一个切片中。

例如下面的代码:

strings.Split("email@email.com", "@")

返回:["email", "email.com"]

strings.SplitAfter("email@email.com", "@")

返回:["email@", "email.com"]

获取["email", "@email.com"] 的最佳方式是什么?

【问题讨论】:

  • 最简单的方法是将分隔符“添加”到每个但返回的切片中的第一项。 play.golang.com/p/sA33rVeJjRt
  • 他所做的基本上是我所做的,但他给了你一个很好用的功能。

标签: string go split substring slice


【解决方案1】:

使用strings.Index找到@并切片得到两部分:

var part1, part2 string
if i := strings.Index(s, "@"); i >= 0 {
    part1, part2 = s[:i], s[i:]
} else {
    // handle case with no @
}

Run it on the playground.

【讨论】:

【解决方案2】:

这对你有用吗?

s := strings.Split("email@email.com", "@")
address, domain := s[0], "@"+s[1]
fmt.Println(address, domain)
// email @email.com

然后梳理并创建一个字符串

var buffer bytes.Buffer
buffer.WriteString(address)
buffer.WriteString(domain)
result := buffer.String()
fmt.Println(result)
// email@email.com

【讨论】:

  • 如果字符串不包含@,则此答案中的代码将出现恐慌。
【解决方案3】:

你可以使用bufio.Scanner:

package main

import (
   "bufio"
   "strings"
)

func email(data []byte, eof bool) (int, []byte, error) {
   for i, b := range data {
      if b == '@' {
         if i > 0 {
            return i, data[:i], nil
         }
         return len(data), data, nil
      }
   }
   return 0, nil, nil
}

func main() {
   s := bufio.NewScanner(strings.NewReader("email@email.com"))
   s.Split(email)
   for s.Scan() {
      println(s.Text())
   }
}

https://golang.org/pkg/bufio#Scanner.Split

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-06
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 2014-06-29
    相关资源
    最近更新 更多