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


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