Home > Enterprise >  Get the next word after you match a word in a string
Get the next word after you match a word in a string

Time:09-05

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".

CodePudding user response:

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])
}
  •  Tags:  
  • go
  • Related