github.com/jxskiss/gopkg@v0.17.3/strutil/strcase.go (about)

     1  package strutil
     2  
     3  import (
     4  	"unicode"
     5  )
     6  
     7  // ToSnakeCase convert the given string to snake case following the Golang format:
     8  // acronyms are converted to lower-case and preceded by an underscore.
     9  func ToSnakeCase(in string) string {
    10  	runes := []rune(in)
    11  	length := len(runes)
    12  
    13  	var out []rune
    14  	for i := 0; i < length; i++ {
    15  		if i > 0 && unicode.IsUpper(runes[i]) &&
    16  			((i+1 < length && unicode.IsLower(runes[i+1])) || unicode.IsLower(runes[i-1])) {
    17  			out = append(out, '_')
    18  		}
    19  		out = append(out, unicode.ToLower(runes[i]))
    20  	}
    21  
    22  	return string(out)
    23  }
    24  
    25  // ToCamelCase converts the given string to CamelCase.
    26  func ToCamelCase(in string) string {
    27  	return string(toCamelCase([]rune(in)))
    28  }
    29  
    30  // ToLowerCamelCase converts the given string to lowerCamelCase.
    31  func ToLowerCamelCase(in string) string {
    32  	out := toCamelCase([]rune(in))
    33  	length := len(out)
    34  	for i := 0; i < length; i++ {
    35  		isUpper := unicode.IsUpper(out[i])
    36  		if isUpper && (i == 0 || i+1 == length || unicode.IsUpper(out[i+1])) {
    37  			out[i] -= 'A' - 'a'
    38  			continue
    39  		}
    40  		break
    41  	}
    42  	return string(out)
    43  }
    44  
    45  func toCamelCase(runes []rune) []rune {
    46  	var out []rune
    47  	var capNext = true
    48  	for _, v := range runes {
    49  		isUpper, isLower := unicode.IsUpper(v), unicode.IsLower(v)
    50  		if capNext && isLower {
    51  			v += 'A' - 'a'
    52  		}
    53  		if isUpper || isLower {
    54  			out = append(out, v)
    55  			capNext = false
    56  		} else if unicode.IsNumber(v) {
    57  			out = append(out, v)
    58  			capNext = true
    59  		} else {
    60  			capNext = v == '_' || v == ' ' || v == '-' || v == '.'
    61  		}
    62  	}
    63  	return out
    64  }