strings方法
index
判断子字符串或字符在父字符串中出现的位置(索引)
Index 返回字符串 str 在字符串 s 中的索引( str 的第一个字符的索引),-1 表示字符串 s 不包含
字符串 str :strings.Index(s, str string) int
LastIndex
返回字符串 str 在字符串 s 中最后出现位置的索引( str 的第一个字符的索引),-1 表示
字符串 s 不包含字符串 str :strings.LastIndex(s, str string) int
IndexRune
如果 ch 是非 ASCII 编码的字符,建议使用以下函数来对字符进行定位:strings.IndexRune(s string, ch int) int
func test12(){ var str string = "学习,就是知已不足,寻找改变的方法,尝试尝试再尝试,并以此为乐...这就是学习" fmt.Printf("The position of \"方法\" is: ") fmt.Printf("%d\n", strings.Index(str, "方法")) fmt.Printf("The position of the first instance of \"学习\" is: ") fmt.Printf("%d\n", strings.Index(str, "学习")) fmt.Printf("The position of the last instance of \"学习\" is: ") fmt.Printf("%d\n", strings.LastIndex(str, "学习")) fmt.Printf("The position of \"哪怕改变再小\" is: ") fmt.Printf("%d\n", strings.Index(str, "哪怕改变再小")) }
输出
The position of "方法" is: 45 The position of the first instance of "学习" is: 0 The position of the last instance of "学习" is: 105 The position of "哪怕改变再小" is: -1
字节与字符串转换
/** func (this *Server) socketParserHandler(client *genTcpServer.Client, fullData []byte) { fmt.Println("original data is", client) strPointerHex := fmt.Sprintf("%p", unsafe.Pointer(client)) fmt.Println("connection is", strPointerHex) strPointerInt := fmt.Sprintf("%d", unsafe.Pointer(client)) fmt.Println("connection is", strPointerInt) i, _ := strconv.ParseInt(strPointerInt, 10, 0) var pointer *genTcpServer.Client pointer = *(**genTcpServer.Client)(unsafe.Pointer(&i)) fmt.Println("connection pointer is", pointer) debugMsg := fmt.Sprintf("%p", unsafe.Pointer(pointer)) fmt.Println("debugMsg is", debugMsg) */ func unsafeTest() { ss := "工工在aaa" s1 := []byte(ss) a := unsafe.Pointer(&s1) //0xc0000a6ee0 取针指指向的地址,不限定类型 fmt.Println(a) bb := (*string)(a) //0xc0000a6ee0 取字节数组的开始地址,确定地址存储的类型是字符串 b := fmt.Sprintf("%v",bb) fmt.Println(b) s2 := *bb fmt.Println(s2) //工工在aaa } func testByte() { ss := "工工在aaa" s1 := []byte(ss) mm := fmt.Sprintf("%v",s1) fmt.Println(mm) ss = ByteArrayToStr(mm) fmt.Println(ss) } //字符串转字节数据-->fmt.Sprintf("%v",s1) 格式化为字符串后-->转回原来的字符串 func ByteArrayToStr(byteStr string) string{ byteStr = strings.TrimLeft(byteStr,"[") byteStr = strings.TrimRight(byteStr,"]") b := strings.Split(byteStr," ") var bn = make([]byte,0) for _,v := range b { i,_ := strconv.Atoi(v) c := byte(i) bn = append(bn,c) } return string(bn) }