Go   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了golang -- 字符串操作大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

相关包有Strings,strconv


  • 判断是否以某字符串打头/结尾
    Strings.HasPrefix(s String,prefix String) bool=> 对应python的str.startswith
    Strings.HasSuffix(s String,suffix String) bool => 对应python的str.endswith

  • 字符串分割
    Strings.Split(s String,sep String) []String => 对应python的str.split

  • 返回子串索引
    Strings.Index(s String,sub String) int => 对应python的str.index
    Strings.LasTindex 最后一个匹配索引

  • 字符串连接
    Strings.Join(a []String,sep String) String =>对应python的str.join

  • 字符串替换
    Strings.replace(s,old,new String,n int) String =>对应python的str.replace

  • 转为大写/小写
    Strings.ToUpper(s String) String
    Strings.ToLower
    对应python的str.upper,str.lower

  • 子串个数

    Strings.Count(s String,sep String) int

    对应python的 str.count

  • Partition
    python的str.partition在解析包时候很好用,这里封装一个

    funcPartition(sString,sepString)(headString,retSepString,tailString){
    //Partition(s,sep)->(head,sep,tail)
    index:=Strings.Index(s,sep)
    ifindex==-1{
    head=s
    retSep=""
    tail=""
    }else{
    head=s[:index]
    retSep=sep
    tail=s[len(head)+len(sep):]
    }
    return
    }

Partition使用

//包格式头(xy)+数据体+尾(..xy...)
//...
_,header,msg:=Partition(data,"xy")
ifheader==""{
//没有头(xy)丢包.(也有可能粘包分包导致"...x",最后一个(注意是一个)字符变成了x,这时要把前面的包丢弃,只保留一个X)
}else{
//do
}

大佬总结

以上是大佬教程为你收集整理的golang -- 字符串操作全部内容,希望文章能够帮你解决golang -- 字符串操作所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。