1. 程式人生 > >String manipulation in Go

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, beginIndex int, endIndex int) string {
 return s[beginIndex:endIndex]
}
  • String to Integer
testN,_ := strconv.Atoi("1234") 
testN += 1 
fmt.Println(testN)

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

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:

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. 

Like this:

Like Loading...