您的位置 首页 golang

[GO语言]Golang String字符串的操作大全

字符串是不可变值类型,内部用指针指向 UTF-8 字节数组。

• 默认值是空字符串 ""。• 用索引号访问某字节,如 s[i]。• 不能用序号获取字节元素指针,&s[i] 非法。 • 不可变类型,无法修改字节数组。• 字节数组尾部不包含 NULL。

使用索引号访问字符 (byte)。

package mainfunc main() {    s := "abc"    println(s[0] == 'x61', s[1] == 'b', s[2] == 0x63)}

输出结果:

true true true

使用 " ` " 定义不做转义处理的原始字符串,支持跨行。

package mainfunc main() {    s := `abrnx00c`    println(s)}

输出结果:

abrnx00c

连接跨行字符串时,"+" 必须在上一行末尾,否则导致编译错误。

package mainimport (    "fmt")func main() {    s := "Hello, " +        "World!"    // s2 := "Hello, "    // +"World!"     //./main.go:11:2: invalid operation: + untyped string    fmt.Println(s)}

支持用两个索引号 ([]) 返回子串。 串依然指向原字节数组,仅修改了指针和 度属性。

package mainimport (    "fmt")func main() {    s := "Hello, World!"    s1 := s[:5]  // Hello    s2 := s[7:]  // World!    s3 := s[1:5] // ello    fmt.Println(s, s1, s2, s3)}

输出结果:

Hello, World! Hello World! ello

单引号字符常量表示 Unicode Code Point, 持 uFFFF、U7FFFFFFF、xFF 格式。
对应 rune 类型,UCS-4。

package mainimport (    "fmt")func main() {    fmt.Printf("%Tn", 'a')    var c1, c2 rune = 'u6211', '们'    println(c1 == '我', string(c2) == "xe4xbbxac")}

输出结果:

int32    // rune 是 int32 的别名 true true

要修改字符串,可先将其转换成 []rune 或 []byte,完成后再转换为 string。无论哪种转换,都会重新分配内存,并复制字节数组。

package mainfunc main() {    s := "abcd"    bs := []byte(s)    bs[1] = 'B'    println(string(bs))    u := "电脑"    us := []rune(u)    us[1] = '话'    println(string(us))}

输出结果:

aBcd电话

for 循环遍历字符串时,也有 byte 和 rune 两种方式。

package mainimport (    "fmt")func main() {    s := "abc汉字"    for i := 0; i < len(s); i++ { // byte        fmt.Printf("%c,", s[i])    }    fmt.Println()    for _, r := range s { // rune        fmt.Printf("%c,", r)    }    fmt.Println()}

输出结果:

a,b,c,æ,±,�,å,­,�,a,b,c,汉,字,

string的底层布局

[GO语言]Golang String字符串的操作大全
image

字符串处理:

判断是不是以某个字符串开头

package mainimport (    "fmt"    "strings")func main() {    str := "hello world"    res0 := strings.HasPrefix(str, "http://")    res1 := strings.HasPrefix(str, "hello")    fmt.Printf("res0 is %vn", res0)    fmt.Printf("res1 is %vn", res1)}

输出结果:

res0 is falseres1 is true

判断是不是以某个字符串结尾

package mainimport (    "fmt"    "strings")func main() {    str := "hello world"    res0 := strings.HasSuffix(str, "http://")    res1 := strings.HasSuffix(str, "world")    fmt.Printf("res0 is %vn", res0)    fmt.Printf("res1 is %vn", res1)}

输出结果:

res0 is falseres1 is true

判断str在s中首次出现的位置,如果没有返回-1

package mainimport (    "fmt"    "strings")func main() {    str := "hello world"    res0 := strings.Index(str, "o")    res1 := strings.Index(str, "i")    fmt.Printf("res0 is %vn", res0)    fmt.Printf("res1 is %vn", res1)}

输出结果:

res0 is 4res1 is -1

判断str在s中最后一次出现的位置,如果没有返回-1

package mainimport (    "fmt"    "strings")func main() {    str := "hello world"    res0 := strings.LastIndex(str, "o")    res1 := strings.LastIndex(str, "i")    fmt.Printf("res0 is %vn", res0)    fmt.Printf("res1 is %vn", res1)}

输出结果:

res0 is 7res1 is -1

字符串替换

package mainimport (    "fmt"    "strings")func main() {    str := "hello world world"    res0 := strings.Replace(str, "world", "golang", 2)    res1 := strings.Replace(str, "world", "golang", 1)    //trings.Replace("原字符串", "被替换的内容", "替换的内容", 替换次数)    fmt.Printf("res0 is %vn", res0)    fmt.Printf("res1 is %vn", res1)}

输出结果:

res0 is hello golang golangres1 is hello golang world

求str含s的次数

package mainimport (    "fmt"    "strings")func main() {    str := "hello world world"    countTime0 := strings.Count(str, "o")    countTime1 := strings.Count(str, "i")    fmt.Printf("countTime0 is %vn", countTime0)    fmt.Printf("countTime1 is %vn", countTime1)}

输出结果:

countTime0 is 3countTime1 is 0

重复 n 次 str

package mainimport (    "fmt"    "strings")func main() {    str := "hello world "    res0 := strings.Repeat(str, 0)    res1 := strings.Repeat(str, 1)    res2 := strings.Repeat(str, 2)    // strings.Repeat("原字符串", 重复次数)    fmt.Printf("res0 is %vn", res0)    fmt.Printf("res1 is %vn", res1)    fmt.Printf("res2 is %vn", res2)}

输出结果:

res0 is res1 is hello world res2 is hello world hello world 

str 转为大写

package mainimport (    "fmt"    "strings")func main() {    str := "hello world "    res := strings.ToUpper(str)    fmt.Printf("res is %vn", res)}

输出结果:

res is HELLO WORLD 

str 转为小写

package mainimport (    "fmt"    "strings")func main() {    str := "HELLO WORLD "    res := strings.ToLower(str)    fmt.Printf("res is %vn", res)}

输出结果:

res is hello world 

去掉 str 首尾的空格

package mainimport (    "fmt"    "strings")func main() {    str := "     hello world     "    res := strings.TrimSpace(str)    fmt.Printf("res is %vn", res)}

去掉字符串首尾指定的字符

package mainimport (    "fmt"    "strings")func main() {    str := "hi , hello world , hi"    res := strings.Trim(str, "hi")    fmt.Printf("res is %vn", res)}

输出结果:

res is  , hello world , 

去掉字符串首指定的字符

package mainimport (    "fmt"    "strings")func main() {    str := "hi , hello world , hi"    res := strings.TrimLeft(str, "hi")    fmt.Printf("res is %vn", res)}

输出结果:

res is  , hello world , hi

去掉字符串尾指定的字符

package mainimport (    "fmt"    "strings")func main() {    str := "hi , hello world , hi"    res := strings.TrimRight(str, "hi")    fmt.Printf("res is %vn", res)}

输出结果:

res is hi , hello world , 

返回str空格分隔的所有子串的slice,

package mainimport (    "fmt"    "strings")func main() {    str := "hello world ,hello golang"    res := strings.Fields(str)    fmt.Printf("res is %vn", res)}

输出结果:

res is [hello world ,hello golang]

返回str 指定字符分隔的所有子串的slice

package mainimport (    "fmt"    "strings")func main() {    str := "hello world ,hello golang"    res := strings.Split(str, "o")    fmt.Printf("res is %vn", res)}

输出结果:

res is [hell  w rld ,hell  g lang]

用指定字符将 string 类型的 slice 中所有元素链接成一个字符串

package mainimport (    "fmt"    "strings")func main() {    str := []string{"hello", "world", "hello", "golang"}    res := strings.Join(str, "++")    fmt.Printf("res is %vn", res)    /*        num := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}        res1 := strings.Join(num, "++")        //  cannot use num (type []int) as type []string in argument to strings.Join        fmt.Println(res1)    */}

输出结果:

res is hello++world++hello++golang

文章来源:智云一二三科技

文章标题:[GO语言]Golang String字符串的操作大全

文章地址:https://www.zhihuclub.com/282.shtml

关于作者: 智云科技

热门文章

评论已关闭

35条评论

  1. For more information on this medication choose from the list of selections below Both brand-name Cialis and tadalafil have been shown to be safe and provide the same treatment effects for erectile dysfunction, but tadalafil is available for a fraction of the price of Cialis

  2. Doing it quickly can cause you to tense up, so make sure to go slow As a result, more than ten restaurants and libraries in the city were closed, what is best medication for erectile dysfunction and all the personnel were arrested, including Han Xizai who had been there

  3. Sex, like a magical happiness ritual, will get you your mutual understanding, love and strong relationship back

  4. An important characteristic of tadalafil is its prolonged period of responsiveness

  5. And above the palm print, there is a desolate power. Clomid or as a generic drug, clomiphene citrate is an fertility medication that comes in a tablet and works to rebalance your hormones.

  6. Women who start NuvaRing postpartum and have not yet had a normal period should use an additional non- hormonal method of contraception for the first seven days.

  7. Slow release formulations will generally degrade or release the F1C from the dosage over a period of about 2 minutes to about 60 minutes or more Pilots suffering from depression are allowed to fly commercial jets if they take one of only four antidepressants; Zoloft, Celexa, Lexapro, Prozac the most activating stimulating of this drug class as opposed to the more tranquilizing

  8. During a single exam, both the heart and vasculature can be simultaneously assessed, an important feature when evaluating patients receiving multiple therapies that can promote injury to multiple components of the CV system, such as cardiomyocytes and arterial endothelial cells that can both experience mitochondrial dysfunction after the administration of anthracycline chemotherapy 64, 65

  9. He wants to be a part of the best offensive line that the franchise has ever seen, and he wants to bring a Super Bowl championship to Philadelphia

  10. EDT 2100 GMT, willinclude measures to cut roaming costs for wireless customers, give consumers more choice on television stations they receiveby cable, and increase high speed broadband networks in ruralareas

  11. Г‚ A few months ago, a Chinese doctor trained in TCM was aboard a flight from China to the UK

  12. ChIP qPCR experiment was performed using NF1 antibody Ab 2 to assess NF1 occupancy at the EREs in GREB1 Region 2, Figure 2C or TFF1 Region 1, Figure 2C in parental or NF1 KO clone 1 MCF 7 cells treated with 4 OHT

  13. However, the main advantage of LDA is that it is a probabilistic model with interpretable topics The patient succumbed on day 8 to hypoxia and bradycardia and arrested on maximum medical therapy

  14. YouTube Browse our videos, discussing the latest in hair transplant surgery and showcasing the amazing results that can be achieved by True Dorin, on YouTube www

  15. Even so, as we will soon see, Nolvadex side effects are for the most part extremely mild and often very rare with proper use; in fact, serious problems are almost unheard of

  16. Since that time, new data have become available, these have been incorporated into the Monograph, and taken into consideration in the present evaluation 8 over his career while Redick, 30, averaged 14

  17. Cardiomyocytes and noncardiomyocytes were isolated from adult male and female mice using a Langendorff free method as previously described 1

  18. Md Matiullah Khan The success of these techniques is reflected in the percentage of pairs that are compatible

  19. 42 In doubtful cases, a histopathology may help to rule out other causes Schedule an appointment at Ginsberg Eye in Naples, FL, to get the help you need

  20. Cholesterol is also a critical component of Vitamin D, a nutrient that similarly plays a very important role in fertility

  21. This cohort study assesses physical activity levels among elderly patients hospitalized for acute medical illness and examines the association between physical activity in the hospital setting and functional decline

  22. Further studies are needed to determine the effects of soy before and after breast cancer diagnosis, in relation to tamoxifen use and breast cancer outcome C The integrated BAC reporter

  23. But if you are not intending this, make people eat, drink, speak, dress, in keeping with their social background, finances and locality

  24. You re taking purim ellipta vs spiriva Li Fung s strong gains today may be quite surprisinggiven its so so earnings, but its forward guidance was a relieffor some

  25. Thus, this makes vitamin D a cheap, inexpensive inotrope, plus one of the strongest anti inflammatory and anti oxidant agents in the human body

  26. For each sample, the signal corresponding to the SRA Del was measured using Quantity One software Bio Rad, Hercules, CA, USA and expressed as a percentage of the corresponding core SRA signal

网站地图