[英]How to find an exact character at a particular position in a string
I have the following string: 我有以下字符串:
absoloute-power
As you can see, there is a "-" at position number 10 in the string. 如您所见,字符串中位置10处有一个“-”。 How do I write the go code to validate if the 10th position of any given string has a "-" in the string? 如何编写go代码以验证给定字符串的第十个位置在字符串中是否有“-”?
In Go, string character values are Unicode characters encoded in UTF-8. 在Go中,字符串字符值是以UTF-8编码的Unicode字符。 UTF-8 is a variable-length encoding which uses one to four bytes per character. UTF-8是其中每个字符使用一个到四个字节的可变长度编码。
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 游乐场: 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: 如果您愿意考虑遇到Unicode替换字符错误,那么以您的示例为例:
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 游乐场: https : //play.golang.org/p/SHbPAnldTyw
You could use a rune-array: 您可以使用符文数组:
text := "ifthisisyourstring"
chars := []rune(text)
if chars[0] == '1' {
// is true
}
As string is an array in fact, you can access the 10th position directly.Of course, need to avoid "out of range " error. 由于字符串实际上是一个数组,因此您可以直接访问第10个位置。当然,需要避免“超出范围”错误。 For the case of the non-ascii encoding, converting it to a rune array 对于非ascii编码,请将其转换为符文数组
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] == '-'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.