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])
fmt.Println(greeting[5])

The result would be  “n“. However, without the character formatter, the result would be the Unicode decimal code 110.

  • Get string length
len(greeting)
  • Substrings
func substring(s string, beginIndex int) string{
return s[beginIndex:]
}

func substring2(s string, beginIdx int, endIdx int) string {
return s[beginIdx:endIdx]
}
  • String to Integer
testN,_ := strconv.Atoi("1234")  
testN += 1
fmt.Println(testN)

strconv package

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

  • Comparing Strings

To compare strings, use the comparison operators ==, < and >

The strings package has a Compare function that comes with a warning that no one should use strings.Compare

https://golang.org/src/strings/compare.go

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"}
countries.Sort()
n := countries.Search( "USA")
fmt.Println(""Result: ", n, countries[n])

}


Result: 3 USA

Sorting Characters in a string

To sort characters in a string, we use the fact that strings in Go can be represented as a slice of runes. We could extend the generic sort function in Go to sort the slice of runes. To use the generic sort, we need to implement sort.Interface – Len, Swap, Less.

type sortRunes []rune 

func (s sortRunes) Less(i, j int) bool {
return s[i] < s[j]
}

func (s sortRunes) Len() int{
return len(s)
}

func (s sortRunes) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}

str1 := "sortthisstring"
s := []rune(str1) sort.Sort(sortRunes(s))

See the full working example here:

https://play.golang.org/p/f7wFD8NX97d

Note the sort package comments, Sort makes one call to data.Len to determine n, and O(n*log(n)) calls to   data.Less and data.Swap. 

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 )

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