C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Return: If the substring is not found within the string, Index returns -1. The search goes from left to right.
Result: This program prints the value "FOUND" because the string "rainbow" is found within "the rainbow."
Golang program that uses index, strings
package main
import (
"fmt"
"strings"
)
func main() {
value1 := "rainbow"
value2 := "the rainbow"
// See if value1 is found in value2.
if strings.Index(value2, value1) != -1 {
fmt.Println("FOUND")
}
}
Output
FOUND
Golang program that uses Index, displays result
package main
import (
"fmt"
"strings"
)
func main() {
value := "cat dog"
// Get index of this substring.
result := strings.Index(value, "dog")
fmt.Println(result)
}
Output
4
Here: The index of the second substring "one," at 8, is located, not the first substring at index 0.
Golang program that uses LastIndex
package main
import (
"fmt"
"strings"
)
func main() {
input := "one two one"
// Get last index, searching from right to left.
i := strings.LastIndex(input, "one")
fmt.Println(i)
}
Output
8
Func: The func passed to IndexFunc can be specified as a local variable. It could be specified directly as an argument.
Further: Any func that receives a rune and returns a bool can be used. The func could use a map or external data source to test chars.
Golang program that uses IndexFunc to find rune
package main
import (
"fmt"
"strings"
)
func main() {
f := func(c rune) bool {
// Return true if colon or space char.
return c == ':' ||
c == ' ';
}
value := "one:two"
// Pass func to method.
result := strings.IndexFunc(value, f)
fmt.Println(result)
value = "one two"
result = strings.IndexFunc(value, f)
fmt.Println(result)
}
Output
3
3
Golang program that uses IndexAny
package main
import (
"fmt"
"strings"
)
func main() {
value := "bird"
// Finds the letter "i" index.
// ... No "a" is found in the string.
result1 := strings.IndexAny(value, "ai")
fmt.Println("RESULT1:", result1, value[result1:result1+1])
// Find index of first character in the set of chars.
result2 := strings.IndexAny(value, "x?rd_")
fmt.Println("RESULT2:", result2, value[result2:result2+1])
}
Output
RESULT1: 1 i
RESULT2: 2 r