github.com/haraldrudell/parl@v0.4.176/pstrings/strings.go (about)

     1  /*
     2  © 2021–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  // Package pstrings provides string fitting, filtered join and quoting of a string slice.
     7  package pstrings
     8  
     9  import (
    10  	"fmt"
    11  	"strings"
    12  )
    13  
    14  // FilteredJoinWithHeading takes a string slice of heading-value pairs and
    15  // only outputs those strings that are non-empty.
    16  // {"head1", "first", "head2, ""} → "head1: first"
    17  func FilteredJoinWithHeading(sList []string, separator ...string) (line string) {
    18  	var sep string
    19  	if len(separator) > 0 {
    20  		sep = separator[0]
    21  	} else {
    22  		sep = "\x20"
    23  	}
    24  	var nonEmpties []string
    25  	for i := 0; i < len(sList)-1; i += 2 {
    26  		heading := sList[i]
    27  		value := sList[i+1]
    28  		if len(value) == 0 {
    29  			continue
    30  		}
    31  		if len(heading) > 0 {
    32  			value = heading + ": " + value
    33  		}
    34  		nonEmpties = append(nonEmpties, value)
    35  	}
    36  	return strings.Join(nonEmpties, sep)
    37  }
    38  
    39  // FilteredJoin is like strings.Join but ignores empty strings.
    40  // defauklt separator is single space \x20
    41  func FilteredJoin(sList []string, separator ...string) (line string) {
    42  	var sep string
    43  	if len(separator) > 0 {
    44  		sep = separator[0]
    45  	} else {
    46  		sep = "\x20"
    47  	}
    48  	var nonEmpties []string
    49  	for _, s := range sList {
    50  		if s != "" {
    51  			nonEmpties = append(nonEmpties, s)
    52  		}
    53  	}
    54  	return strings.Join(nonEmpties, sep)
    55  }
    56  
    57  // QuoteList formats a string slice using %q into a single space-separated string
    58  func QuoteList(strs []string) string {
    59  	strs2 := make([]string, len(strs))
    60  	for i, str := range strs {
    61  		strs2[i] = fmt.Sprintf("%q", str)
    62  	}
    63  	return strings.Join(strs2, "\x20")
    64  }
    65  
    66  func StrSliceContains(ss []string, s string) bool {
    67  	for _, v := range ss {
    68  		if v == s {
    69  			return true
    70  		}
    71  	}
    72  	return false
    73  }