I have the following string:
absoloute-power
As you can see, there is a "-" at position number 10 in the string. How do I write the go code to validate if the 10th position of any given string has a "-" in the string?
You could use a rune-array:
text := "ifthisisyourstring"
chars := []rune(text)
if chars[0] == '1' {
// is true
}
In Go, string character values are Unicode characters encoded in UTF-8. UTF-8 is a variable-length encoding which uses one to four bytes per character.
For your example:
package main
import (
"fmt"
"unicode/utf8"
)
func is10Hyphen(s string) bool {
for n := 1; len(s) > 0; n++ {
r, size := utf8.DecodeRuneInString(s)
if r == utf8.RuneError && (size == 0 || size == 1) {
return false
}
if n == 10 {
return r == '-'
}
s = s[size:]
}
return false
}
func main() {
s := "absoloute-power"
fmt.Println(is10Hyphen(s))
s = "absoloute+power"
fmt.Println(is10Hyphen(s))
s = "absoloute"
fmt.Println(is10Hyphen(s))
}
Playground: https://play.golang.org/p/h9rMQWWAdvb
Output:
true
false
false
If you are willing to consider encountering the Unicode replacement character an error, then for your example:
func is10Hyphen(s string) bool {
n := 0
for _, r := range s {
if r == utf8.RuneError {
return false
}
n++
if n == 10 {
return r == '-'
}
}
return false
}
Playground: https://play.golang.org/p/SHbPAnldTyw
As string is an array in fact, you can access the 10th position directly.Of course, need to avoid "out of range " error. For the case of the non-ascii encoding, converting it to a rune array
package main
import (
"fmt"
)
func main() {
fmt.Println(Check("213123-dasdas"))
fmt.Println(Check("213123sdas"))
fmt.Println(Check("213123das-das"))
fmt.Println(Check("213123dasda-s"))
fmt.Println(Check("---------2----------"))
}
func Check(ss string) bool {
r = []rune(ss)
if len(r) < 10 {
return false
}
return ss[r] == '-'
}