SplitN backwards?

huangapple go评论103阅读模式
英文:

SplitN backwards?

问题

我有一个字符串,它的开头总是一个会每次改变的句子,但结尾是时间和日期。例如:"我去商店了 12:00 12/12/12" 或者 "我喜欢吐司 11:20 13/10/14"。

我想从这些字符串中提取出时间。是否可以从右侧开始使用 SplitN 函数进行分割?

英文:

I have a string that will always start with a sentence that well change each time but end with time then date. For example "I went to the shop 12:00 12/12/12" or "I like toast 11:20 13/10/14".

I want to extract the time out of these strings. Is it possible to do SplitN starting from the right?

答案1

得分: 1

如果你知道它总是以时间和日期结尾,为什么不用split函数反向操作呢?

Playground链接

package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "我去了商店 12:00 12/12/12"
	chunks := strings.Split(s, " ")
	time := chunks[len(chunks)-2]
	fmt.Println(time)
}
英文:

If you know that it will always end with time and then date why not just go backwards with split?

Playground link

package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "I went to the shop 12:00 12/12/12"
	chunks := strings.Split(s, " ")
	time := chunks[len(chunks)-2]
	fmt.Println(time)
}

huangapple
  • 本文由 发表于 2016年9月2日 05:45:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/39281356.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定