Golang的strings.TrimSpace()

今天顺便把另一个 golang中的 strings.TrimSpace()函数。

其中值得关注的一个方式就是关于 asciiSpace的使用方式,其实就是一种 array的初始化方式。

这个函数的定义方式如下:

var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1}

// TrimSpace returns a slice of the string s, with all leading
// and trailing white space removed, as defined by Unicode.
func TrimSpace(s string) string {
   // Fast path for ASCII: look for the first ASCII non-space byte
   start := 0
   for ; start < len(s); start++ {
      c := s[start]
      if c >= utf8.RuneSelf {
         // If we run into a non-ASCII byte, fall back to the
         // slower unicode-aware method on the remaining bytes
         return TrimFunc(s[start:], unicode.IsSpace)
      }
      if asciiSpace[c] == 0 {
         break
      }
   }

   // Now look for the first ASCII non-space byte from the end
   stop := len(s)
   for ; stop > start; stop-- {
      c := s[stop-1]
      if c >= utf8.RuneSelf {
         // start has been already trimmed above, should trim end only
         return TrimRightFunc(s[start:stop], unicode.IsSpace)
      }
      if asciiSpace[c] == 0 {
         break
      }
   }

   // At this point s[start:stop] starts and ends with an ASCII
   // non-space bytes, so we're done. Non-ASCII cases have already
   // been handled above.
   return s[start:stop]
}

其实就是考虑到类似于制表符等空格符号。

package main

import (
	"fmt"
)

type asciiSet [8]uint32

var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1}

func main() {
	for index, value := range asciiSpace {
		if value != 0 {
			fmt.Println(index, value)
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值