Uncategorized

String manipulation in Go

Basic Operations

  • Get char array of a String

greeting := "Comment allez-vous"
greeingCharacterArr := []rune(greeting)
  • Get a char at the specific index

fmt.Printf("%c", greeting[5])

Result: n

Without the character formatter, the result would be the Unicode decimal code E.g.

fmt.Println(greeting[5])
Result: 110
  • Get string length

len(greeting)
  • Substrings

 

func substring(s string, beginIndex int) string {
 return s[beginIndex:]
}

func substring2(s string, beginIndex int, endIndex int) string {
 return s[beginIndex:endIndex]
}

  • String to Integer
testN,_ := strconv.Atoi("1234") 
testN += 1 
fmt.Println(testN)

strconv package

Above examples : https://play.golang.org/p/kds_Lu9HyTJ

Sorting and Searching Strings in Golang

The sort package in Go has some very useful methods for sorting and searching slices and strings.

The sort.StringSlice attaches the methods of Interface to []string, sorting in increasing order. https://golang.org/pkg/sort/#StringSlice

E.g.

package main
import ( "fmt" "sort")
func main() { 
    countries := sort.StringSlice{"USA", "India", "South africa", "Libya"}
    countries.Sort() 
    n := countries.Search( "USA")
    fmt.Println(""Result: ", n, countries[n])
}

Result: 3 USA

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com 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