Golang--string manipulation

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Related packages are strings, StrConv


  • Determine whether to begin/end with a string
    Strings. Hasprefix (s string, prefix string) bool = Str.startswith corresponding to Python
    Strings. Hassuffix (s string, suffix string) bool = Str.endswith corresponding to Python

  • String segmentation
    Strings. Split (S string, Sep string) []string = Str.split for Python

  • Returns the substring index
    Strings. Index (S string, sub string) int = = corresponds to Python's str.index
    Strings. LastIndex Last matching Index

  • String connection
    Strings. Join (A []string, Sep string) string = = corresponds to Python's str.join

  • String substitution
    Strings. Replace (S, old, new string, n int) string = = corresponds to Python's str.replace

  • Convert to uppercase/lowercase
    Strings. ToUpper (s string) string
    Strings. ToLower
    Corresponding to Python's str.upper,str.lower

  • Number of sub-strings

    Strings. Count (S string, sep string) int

    Corresponding to Python's Str.count

  • Partition
    Python's str.partition is useful when parsing packages, encapsulating a

    func partition (s string, sep  String)   (head string, retsep string, tail string)  {      partition (S, SEP)  ->  (Head, sep, tail)     index : = strings. Index (S, SEP)     if index == -1 {         head = s        retSep =  ""         tail =  ""     } else {         head = s[:index]         retsep = sep        tail = s[len (head) +len (Sep):]    }    return} 

Partition use

Package format header (XY) + Data body + tail (... XY ...) ... _, header, msg: = Partition (data, "XY") if Header = = "" {//No header (XY) drops. (It is also possible that the sticky packet sub-package causes "... x", the last (note is a) character becomes x, when the front packet is discarded, only one x is left)} else {//do}





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.