在字符串中匹配一个单词后,获取其后面的单词。

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

Get the next word after you match a word in a string

问题

我正在尝试获取字符串中匹配项后面的下一个单词。

例如:

var somestring string = "Hello this is just a random string"

要匹配单词,我可以这样做:

strings.Contains(somestring, "just")

在这种情况下,我想要获取的是 "a"。

英文:

I am trying to get the next word after a match in a string.

For instance

var somestring string = "Hello this is just a random string"

to match the word I do this

strings.Contains(somestring, "just")

and in this case i would want to get the "a".

答案1

得分: 3

package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "Hello this is just a random string"
	// 找到字符串 "just" 的索引
	index := strings.Index(s, "just")
	fmt.Println(index)
	// 获取 "just" 后面的下一个单词
	word := strings.Fields(s[index:])
	fmt.Println(word[1])
}

这是一个Go语言的代码片段,它的功能是找到字符串中特定单词的索引,并获取该单词后面的下一个单词。在这个例子中,它找到了字符串 "just" 的索引,并输出了该索引值。然后,它使用字符串切片和字符串分割函数获取了 "just" 后面的下一个单词,并将其输出。

英文:
package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "Hello this is just a random string"
	// find the index of string "just"
	index := strings.Index(s, "just")
	fmt.Println(index)
    // get next single word after "just"
    word := strings.Fields(s[index:])
    fmt.Println(word[1])
}

huangapple
  • 本文由 发表于 2022年9月5日 13:25:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/73604820.html
匿名

发表评论

匿名网友

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

确定