Advance functions with strings

The standard library’s strings package provides many useful string-related functions. Here are some examples to give you a sense of the package.

package main

import (

func main() {

    fmt.Println("Contains:  ", strings.Contains("test", "es"))
    fmt.Println("Count:     ", strings.Count("test", "t"))
    fmt.Println("HasPrefix: ", strings.HasPrefix("test", "te"))
    fmt.Println("HasSuffix: ", strings.HasSuffix("test", "st"))
    fmt.Println("Index:     ", strings.Index("test", "e"))
    fmt.Println("Join:      ", strings.Join([]string{"a", "b"}, "-"))
    fmt.Println("Repeat:    ", strings.Repeat("a", 5))
    fmt.Println("Replace:   ", strings.Replace("foo", "o", "0", -1))
    fmt.Println("Replace:   ", strings.Replace("foo", "o", "0", 1))
    fmt.Println("Split:     ", strings.Split("a-b-c-d-e", "-"))
    fmt.Println("ToLower:   ", strings.ToLower("TEST"))
    fmt.Println("ToUpper:   ", strings.ToUpper("test"))

    fmt.Println("Len: ", len("hello"))
    fmt.Println("Char:", "hello"[1])
Contains:   true
Count:      2
HasPrefix:  true
HasSuffix:  true
Index:      1
Join:       a-b
Repeat:     aaaaa
Replace:    f00
Replace:    f0o
Split:      [a b c d e]
ToLower:    test
ToUpper:    TEST

Len:  5
Char: 101

Convert string to int

i , err := strconv.Atoi("1")

Convert string to int

istr := strconv.Itoa(i)

View on github


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s