Searching an element of string type in Golang slice
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice.
In the Go slice, you can search an element of string type in the given slice of strings with the help of SearchStrings() function. This function searches for the given element in a sorted slice of strings and returns the index of that element if present in the given slice. And if the given element is not available in the slice(it could be len(s_slice)), then it returns the index to insert the element in the slice. The specified slice must be sorted in ascending order. It is defined under the sort package so, you have to import sort package in your program for accessing SearchStrings function.
Syntax:
func SearchStrings(s_slice []string, s string64) int
Example 1:
package main
import (
"fmt"
"sort"
)
func main() {
slice_1 := []string{ "C" , "Go" , "Java" , "C#" , "Ruby" }
slice_2 := []string{ "GEEKs" , "123geeks" , "gfg" , "GeeksforGeeks" }
var f1, f2, f3 string
f1 = "GEEKs"
f2 = "C"
f3 = "gfg"
sort.Strings(slice_1)
sort.Strings(slice_2)
fmt.Println( "Slice 1: " , slice_1)
fmt.Println( "Slice 2: " , slice_2)
res1 := sort.SearchStrings(slice_1, f1)
res2 := sort.SearchStrings(slice_2, f2)
res3 := sort.SearchStrings(slice_2, f3)
fmt.Println( "Result 1: " , res1)
fmt.Println( "Result 2: " , res2)
fmt.Println( "Result 3: " , res3)
}
|
Output:
Slice 1: [C C# Go Java Ruby]
Slice 2: [123geeks GEEKs GeeksforGeeks gfg]
Result 1: 2
Result 2: 1
Result 3: 3
Example 2:
package main
import (
"fmt"
"sort"
)
func main() {
res1 := sort.SearchStrings([]string{ "apple" , "banana" ,
"kiwi" , "orange" }, "kiwi" )
res2 := sort.SearchStrings([]string{ "Cat" , "Cow" ,
"Dog" , "Parrot" }, "Cat" )
fmt.Println( "Result 1: " , res1)
fmt.Println( "Result 2: " , res2)
}
|
Output:
Result 1: 2
Result 2: 0
Last Updated :
05 Sep, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...