常用的截取字符串方法JS和Golang实现

JS中截取字符串很简单,直接使用substr函数

substr() 方法可在字符串中截取从开始下标开始的指定数目的字符。下标是从0开始算

例如:

"21".substr(0,1)   返回2

golang实现的substr

复制代码
// 截取字符串,支持多字节字符
// start:起始下标,负数从从尾部开始,最后一个为-1
// length:截取长度,负数表示截取到末尾
func SubStr(str string, start int, length int) (result string) {
    s := []rune(str)
    total := len(s)
    if total == 0 {
        return
    }
    // 允许从尾部开始计算
    if start < 0 {
        start = total + start
        if start < 0 {
            return
        }
    }
    if start > total {
        return
    }
    // 到末尾
    if length < 0 {
        length = total
    }

    end := start + length
    if end > total {
        result = string(s[start:])
    } else {
        result = string(s[start:end])
    }

    return
}
复制代码

SubStr("hello",0,1)  返回h

如果倒着截取,负数就是倒着取,倒着取第一个,SubStr("hello",-1,1) 返回 o

posted @   唯一客服系统开发笔记  阅读(97)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
历史上的今天:
2018-05-05 [日常] Go语言圣经-基于select的多路复用习题
2018-05-05 [日常] Go语言圣经--并发的web爬虫
2016-05-05 [javaSE] 网络编程(TCP,UDP,Socket特点)
2016-05-05 [javaSE] 网络编程(概述)
2016-05-05 [PHP] 商品类型规格属性后台管理(代码流程备忘)
点击右上角即可分享
微信分享提示
1
chat with us