5

[Golang] Remove Leading and Trailing Empty Strings in String Array

 2 years ago
source link: http://siongui.github.io/2017/01/19/go-remove-leading-and-trailing-empty-strings-in-string-slice/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

[Golang] Remove Leading and Trailing Empty Strings in String Array

January 19, 2017

Remove leading and trailing empty strings in string array/slice via Golang. This is similar to removing leading and trailing whitespaces in a string, but in two dimension.

Run code on Go Playground

// Remove leading and trailing empty strings in string array
package main

import (
      "fmt"
)

func RemoveLeadingEmptyStringsInStringArray(sa []string) []string {
      firstNonEmptyStringIndex := 0
      for i := 0; i < len(sa); i++ {
              if sa[i] == "" {
                      firstNonEmptyStringIndex++
              } else {
                      break
              }
      }
      return sa[firstNonEmptyStringIndex:len(sa)]
}

func RemoveTrailingEmptyStringsInStringArray(sa []string) []string {
      lastNonEmptyStringIndex := len(sa) - 1
      for i := lastNonEmptyStringIndex; i >= 0; i-- {
              if sa[i] == "" {
                      lastNonEmptyStringIndex--
              } else {
                      break
              }
      }
      return sa[0 : lastNonEmptyStringIndex+1]
}

func main() {
      testStringArray := []string{"", "", "aa", "bb", "cc", "", "", ""}

      trailingTrimed := RemoveTrailingEmptyStringsInStringArray(testStringArray)
      for _, str := range trailingTrimed {
              if str == "" {
                      fmt.Println("nil")
              } else {
                      fmt.Println(str)
              }
      }

      fmt.Println("----")
      leadingTrailingTrimed := RemoveLeadingEmptyStringsInStringArray(trailingTrimed)
      for _, str := range leadingTrailingTrimed {
              if str == "" {
                      fmt.Println("nil")
              } else {
                      fmt.Println(str)
              }
      }
}

Tested on: Ubuntu Linux 16.10, Go 1.7.4 & Go Playground.


References:

[1]Go Slices: usage and internals - The Go Blog

[2]Zero values - A Tour of Go

[3]Avoiding partially constructed variables : golang


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK