当前位置: 首页>>代码示例>>Golang>>正文


Golang utf8.RuneCountInString函数代码示例

本文整理汇总了Golang中unicode/utf8.RuneCountInString函数的典型用法代码示例。如果您正苦于以下问题:Golang RuneCountInString函数的具体用法?Golang RuneCountInString怎么用?Golang RuneCountInString使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了RuneCountInString函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: NewLabel

// NewLabel returns a new label whos name consists of a prefix followed by
// some digits which make it unique.
//
// Only the first length characters of the prefix are used, and the prefix must
// not end with a digit. If no prefix is given, then the default is used.
//
// Label is initially not initally placed.
func NewLabel(prefix string) *Label {

	l := &Label{
		count:  count,
		length: 5,
		prefix: "label",
	}

	if utf8.RuneCountInString(prefix) > utf8.RuneCountInString(l.prefix) {
		l.prefix = prefix[:utf8.RuneCountInString(prefix)-1]
	}

	lastRune, _ := utf8.DecodeLastRuneInString(l.prefix)

	if prefix == "main" {
		l.name = "main"
		return l
	}

	if unicode.IsDigit(lastRune) {
		log.Fatal("label ended with a digit")
	}

	l.name = l.prefix + strconv.Itoa(l.count)
	count++
	return l
}
开发者ID:jackspirou,项目名称:chip,代码行数:34,代码来源:label.go

示例2: Event

func (c *Client) Event(title string, text string, eo *EventOpts) error {
	var b bytes.Buffer
	fmt.Fprintf(&b, "_e{%d,%d}:%s|%s|t:%s", utf8.RuneCountInString(title),
		utf8.RuneCountInString(text), title, text, eo.AlertType)

	if eo.SourceTypeName != "" {
		fmt.Fprintf(&b, "|s:%s", eo.SourceTypeName)
	}
	if !eo.DateHappened.IsZero() {
		fmt.Fprintf(&b, "|d:%d", eo.DateHappened.Unix())
	}
	if eo.Priority != "" {
		fmt.Fprintf(&b, "|p:%s", eo.Priority)
	}
	if eo.Host != "" {
		fmt.Fprintf(&b, "|h:%s", eo.Host)
	}
	if eo.AggregationKey != "" {
		fmt.Fprintf(&b, "|k:%s", eo.AggregationKey)
	}
	tags := append(c.Tags, eo.Tags...)
	format := "|#%s"
	for _, t := range tags {
		fmt.Fprintf(&b, format, t)
		format = ",%s"
	}

	bytes := b.Bytes()
	if len(bytes) > maxEventBytes {
		return fmt.Errorf("Event '%s' payload is too big (more that 8KB), event discarded", title)
	}
	_, err := c.conn.Write(bytes)
	return err
}
开发者ID:debraj-manna,项目名称:go-dogstatsd,代码行数:34,代码来源:dogstatsd.go

示例3: DiffToDelta

// DiffToDelta crushes the diff into an encoded string which describes the
// operations required to transform text1 into text2.
// E.g. =3\t-2\t+ing  -> Keep 3 chars, delete 2 chars, insert 'ing'.
// Operations are tab-separated.  Inserted text is escaped using %xx
// notation.
func DiffToDelta(diffs []Diff) string {
	var buf bytes.Buffer
	for _, d := range diffs {
		switch d.Type {
		case DiffInsert:
			buf.WriteString("+")
			buf.WriteString(
				strings.Replace(url.QueryEscape(d.Text), "+", " ", -1),
			)
			buf.WriteString("\t")
			break
		case DiffDelete:
			buf.WriteString("-")
			buf.WriteString(strconv.Itoa(utf8.RuneCountInString(d.Text)))
			buf.WriteString("\t")
			break
		case DiffEqual:
			buf.WriteString("=")
			buf.WriteString(strconv.Itoa(utf8.RuneCountInString(d.Text)))
			buf.WriteString("\t")
			break
		}
	}
	delta := buf.String()
	if len(delta) != 0 {
		// Strip off trailing tab character.
		delta = delta[0 : utf8.RuneCountInString(delta)-1]
		delta = unescaper.Replace(delta)
	}
	return delta
}
开发者ID:e8vm,项目名称:shanhu,代码行数:36,代码来源:diff_to_delta.go

示例4: checkTrim

func checkTrim(t string) bool {
	diff := ((utf8.RuneCountInString(t) - len(t)) / 2)
	if utf8.RuneCountInString(t) > (titleCount + diff) {
		return true
	}
	return false
}
开发者ID:kyokomi,项目名称:gitlab-cli,代码行数:7,代码来源:gitlab.go

示例5: ZipStrByGoroutine

func ZipStrByGoroutine(s1, s2 string) string {
	zippedLength := utf8.RuneCountInString(s1) + utf8.RuneCountInString(s2)
	zipped := make([]rune, zippedLength)
	recvCh := make(chan rune)
	switchCh1 := make(chan struct{})
	switchCh2 := make(chan struct{})

	go func() {
		for _, r := range s1 {
			<-switchCh1
			recvCh <- r
			switchCh2 <- struct{}{}
		}
	}()
	go func() {
		for _, r := range s2 {
			<-switchCh2
			recvCh <- r
			switchCh1 <- struct{}{}
		}
	}()

	i := 0
	switchCh1 <- struct{}{}
	for r := range recvCh {
		zipped[i] = r
		i++
		if i == zippedLength {
			break
		}
	}

	return string(zipped)
}
开发者ID:Pandaman,项目名称:natural-language-processing100-practice,代码行数:34,代码来源:main.go

示例6: ValidateLengthOf

func ValidateLengthOf(resource Resource, attribute string, rule string, chars int) {
	value := reflect.ValueOf(resource).Elem()

	value = reflect.Indirect(value).FieldByName(attribute)

	switch rule {
	case "at least":
		if utf8.RuneCountInString(value.String()) < chars {
			message := fmt.Sprintf("length can't be less than %d characters", chars)

			resource.Errors().Add(attribute, message)
		}
	case "at most":
		if utf8.RuneCountInString(value.String()) > chars {
			message := fmt.Sprintf("length can't be more than %d characters", chars)

			resource.Errors().Add(attribute, message)
		}
	case "exactly":
		if utf8.RuneCountInString(value.String()) != chars {
			message := fmt.Sprintf("length must equal %d characters", chars)

			resource.Errors().Add(attribute, message)
		}
	}
}
开发者ID:tksasha,项目名称:go-balance-backend,代码行数:26,代码来源:length_of.go

示例7: saveConfig

func saveConfig(w io.Writer, obsKeys map[string]string) {
	// find flags pointing to the same variable. We will only write the longest
	// named flag to the config file, the shorthand version is ignored.
	deduped := make(map[flag.Value]flag.Flag)
	flag.VisitAll(func(f *flag.Flag) {
		if cur, ok := deduped[f.Value]; !ok || utf8.RuneCountInString(f.Name) > utf8.RuneCountInString(cur.Name) {
			deduped[f.Value] = *f
		}
	})
	flag.VisitAll(func(f *flag.Flag) {
		if cur, ok := deduped[f.Value]; ok && cur.Name == f.Name {
			_, usage := flag.UnquoteUsage(f)
			usage = strings.Replace(usage, "\n    \t", "\n# ", -1)
			fmt.Fprintf(w, "\n# %s (default %v)\n", usage, f.DefValue)
			fmt.Fprintf(w, "%s=%v\n", f.Name, f.Value.String())
		}
	})

	// if we have obsolete keys left from the old config, preserve them in an
	// additional section at the end of the file
	if obsKeys != nil && len(obsKeys) > 0 {
		fmt.Fprintln(w, "\n\n# The following options are probably deprecated and not used currently!")
		for key, val := range obsKeys {
			fmt.Fprintf(w, "%v=%v\n", key, val)
		}
	}
}
开发者ID:schachmat,项目名称:ingo,代码行数:27,代码来源:in.go

示例8: DrawLabel

func DrawLabel(s *svg.SVG, bs string) *BrailleCanvas {
	var c BrailleCanvas

	// TODO: they hard coded
	c.dotSize = 12
	c.pageMarginTop = 3
	c.pageMarginBottom = 3
	c.pageMarginLeft = 3
	c.pageMarginRight = 3
	c.gapCell = 3

	c.canvasW = c.pageMarginLeft + c.pageMarginRight
	c.canvasW += c.dotSize * 2 * utf8.RuneCountInString(bs)
	c.canvasW += c.gapCell*utf8.RuneCountInString(bs) - 1

	c.canvasH = c.pageMarginTop + c.pageMarginBottom
	c.canvasH += c.dotSize * 3

	s.Start(c.canvasW, c.canvasH)

	x := c.pageMarginLeft
	y := c.pageMarginTop
	for _, b := range bs {
		if b&0x2800 != 0x2800 {
			log.Printf("0x%x is not a braille character!\n", b)
			continue
		}
		Draw(s, b, x, y, c.dotSize)
		x += (c.dotSize * 2) + c.gapCell
	}

	return &c
}
开发者ID:suapapa,项目名称:go_braille,代码行数:33,代码来源:svg.go

示例9: DiffToDelta

// DiffToDelta crushes the diff into an encoded string which describes the operations required to transform text1 into text2.
// E.g. =3\t-2\t+ing  -> Keep 3 chars, delete 2 chars, insert 'ing'. Operations are tab-separated.  Inserted text is escaped using %xx notation.
func (dmp *DiffMatchPatch) DiffToDelta(diffs []Diff) string {
	var text bytes.Buffer
	for _, aDiff := range diffs {
		switch aDiff.Type {
		case DiffInsert:
			_, _ = text.WriteString("+")
			_, _ = text.WriteString(strings.Replace(url.QueryEscape(aDiff.Text), "+", " ", -1))
			_, _ = text.WriteString("\t")
			break
		case DiffDelete:
			_, _ = text.WriteString("-")
			_, _ = text.WriteString(strconv.Itoa(utf8.RuneCountInString(aDiff.Text)))
			_, _ = text.WriteString("\t")
			break
		case DiffEqual:
			_, _ = text.WriteString("=")
			_, _ = text.WriteString(strconv.Itoa(utf8.RuneCountInString(aDiff.Text)))
			_, _ = text.WriteString("\t")
			break
		}
	}
	delta := text.String()
	if len(delta) != 0 {
		// Strip off trailing tab character.
		delta = delta[0 : utf8.RuneCountInString(delta)-1]
		delta = unescaper.Replace(delta)
	}
	return delta
}
开发者ID:sergi,项目名称:go-diff,代码行数:31,代码来源:diff.go

示例10: AreOneEditAway

func AreOneEditAway(input1, input2 string) bool {
	len1 := utf8.RuneCountInString(input1)
	len2 := utf8.RuneCountInString(input2)
	if len1 != len2 && len1-1 != len2 && len2-1 != len1 {
		return false
	}
	if len1 == len2 { // must be one replacement
		var width1, width2 int
		var r1, r2 rune
		diffSeen := false
		for i, j := 0, 0; i < len1 || j < len2; i, j = i+width1, j+width2 {
			r1, width1 = utf8.DecodeRuneInString(input1[i:])
			r2, width2 = utf8.DecodeRuneInString(input2[j:])
			if r1 != r2 {
				if diffSeen {
					return false
				} else {
					diffSeen = true
				}
			}
		}
		return true
	} else if len1-1 == len2 { // input1 must be a removal from input2
		return oneRemovalAway(input2, input1)
	} else { //if len2-1 == len1 { // input2 must be a removal from input1
		return oneRemovalAway(input1, input2)
	}
}
开发者ID:lee-woodridge,项目名称:CtCI-6th-Edition,代码行数:28,代码来源:problem5.go

示例11: cellValue

func (t *PrintableTable) cellValue(col int, value string) string {
	padding := ""

	if col < len(t.headers)-1 {
		var count int

		if utf8.RuneCountInString(value) == len(value) {
			if t.maxRuneCountLengths[col] == t.maxStringLengths[col] {
				count = t.maxRuneCountLengths[col] - utf8.RuneCountInString(Decolorize(value))
			} else {
				count = t.maxRuneCountLengths[col] - len(Decolorize(value))
			}
		} else {
			if t.maxRuneCountLengths[col] == t.maxStringLengths[col] {
				count = t.maxRuneCountLengths[col] - len(Decolorize(value)) + utf8.RuneCountInString(Decolorize(value))
			} else {
				count = t.maxStringLengths[col] - len(Decolorize(value))
			}
		}

		padding = strings.Repeat(" ", count)
	}

	return fmt.Sprintf("%s%s   ", value, padding)
}
开发者ID:pivotal-cf,项目名称:cf-watch,代码行数:25,代码来源:table.go

示例12: Worlds

// слово
func (l *Lorem) Worlds(num int) string {

	if num == 0 {
		return ""
	}

	var worlds []string
	result := ""
	k := 0
	for i := 0; i < num; i++ {
		if len(worlds) == 0 || k >= len(worlds) {
			speech := l.Speech(1)
			worlds = strings.Split(speech[:utf8.RuneCountInString(speech)-1], " ")
			k = 0
		}

		result += worlds[k]
		if i < num-1 {
			result += " "
		}

		k++
	}

	if result[utf8.RuneCountInString(result)-1:] == "," {
		result = result[:utf8.RuneCountInString(result)-1]
	}

	return result + ". "
}
开发者ID:e154,项目名称:vydumschik,代码行数:31,代码来源:lorem.go

示例13: resetPassword

func resetPassword(app *Application, answer *model.SecurityAnswer, token *model.Token, r *http.Request) error {
	ans := r.FormValue("answer")
	pass := r.FormValue("password")
	pass2 := r.FormValue("password2")

	if len(pass) < viper.GetInt("min_passwd_len") || len(pass2) < viper.GetInt("min_passwd_len") {
		return errors.New(fmt.Sprintf("Please set a password at least %d characters in length.", viper.GetInt("min_passwd_len")))
	}

	if pass != pass2 {
		return errors.New("Password do not match. Please confirm your password.")
	}

	if utf8.RuneCountInString(ans) < 2 || utf8.RuneCountInString(ans) > 100 {
		return errors.New("Invalid answer. Must be between 2 and 100 characters long.")
	}

	err := bcrypt.CompareHashAndPassword([]byte(answer.Answer), []byte(ans))
	if err != nil {
		return errors.New("The security answer you provided does not match. Please check that you are entering the correct answer.")
	}

	// Setup password in FreeIPA
	err = setPassword(token.UserName, "", pass)
	if err != nil {
		if ierr, ok := err.(*ipa.ErrPasswordPolicy); ok {
			logrus.WithFields(logrus.Fields{
				"uid":   token.UserName,
				"error": ierr.Error(),
			}).Error("password does not conform to policy")
			return errors.New("Your password is too weak. Please ensure your password includes a number and lower/upper case character")
		}

		if ierr, ok := err.(*ipa.ErrInvalidPassword); ok {
			logrus.WithFields(logrus.Fields{
				"uid":   token.UserName,
				"error": ierr.Error(),
			}).Error("invalid password from FreeIPA")
			return errors.New("Invalid password.")
		}

		logrus.WithFields(logrus.Fields{
			"uid":   token.UserName,
			"error": err.Error(),
		}).Error("failed to set user password in FreeIPA")
		return errors.New("Fatal system error")
	}

	// Destroy token
	err = model.DestroyToken(app.db, token.Token)
	if err != nil {
		logrus.WithFields(logrus.Fields{
			"uid":   token.UserName,
			"error": err.Error(),
		}).Error("failed to remove token from database")
		return errors.New("Fatal system error")
	}

	return nil
}
开发者ID:HeWhoWas,项目名称:mokey,代码行数:60,代码来源:handlers.go

示例14: Valid

func (nv *stringValidater) Valid(source string, opt *FieldOption) (vr *ValidResult) {
	source, vr = nv.baseValidater.Valid(source, opt)
	if vr.IsValid || vr.ErrorMsg != "" {
		return vr
	}
	if opt.Range[0] > 0 && utf8.RuneCountInString(source) < opt.Range[0] {
		if opt.Range[1] > 0 {
			vr.ErrorMsg = strings.Replace(
				getOrDefault(opt.ErrorMsgs, "range", MST_RANGE_LENGTH),
				"{0}", strconv.Itoa(opt.Range[0]), -1)
			vr.ErrorMsg = strings.Replace(vr.ErrorMsg, "{1}", strconv.Itoa(opt.Range[1]), -1)
		} else {
			vr.ErrorMsg = strings.Replace(
				getOrDefault(opt.ErrorMsgs, "min", MSG_MIN_LENGTH), "{0}", strconv.Itoa(opt.Range[0]), -1)
		}
		return vr
	}
	if opt.Range[1] > 0 && utf8.RuneCountInString(source) > opt.Range[1] {
		if opt.Range[0] > 0 {
			vr.ErrorMsg = strings.Replace(
				getOrDefault(opt.ErrorMsgs, "range", MST_RANGE_LENGTH), "{0}", strconv.Itoa(opt.Range[0]), -1)
			vr.ErrorMsg = strings.Replace(vr.ErrorMsg, "{1}", strconv.Itoa(opt.Range[1]), -1)
		} else {
			vr.ErrorMsg = strings.Replace(
				getOrDefault(opt.ErrorMsgs, "max", MSG_MAX_LENGTH), "{0}", strconv.Itoa(opt.Range[1]), -1)
		}
		return vr
	}
	vr.IsValid = true
	vr.CleanValue = source

	return vr
}
开发者ID:jango2015,项目名称:goku,代码行数:33,代码来源:validater.go

示例15: IsValid

// IsValid validates the user and returns an error if it isn't configured
// correctly.
func (u *User) IsValid() *AppError {

	if len(u.Id) != 26 {
		return NewLocAppError("User.IsValid", "model.user.is_valid.id.app_error", nil, "")
	}

	if u.CreateAt == 0 {
		return NewLocAppError("User.IsValid", "model.user.is_valid.create_at.app_error", nil, "user_id="+u.Id)
	}

	if u.UpdateAt == 0 {
		return NewLocAppError("User.IsValid", "model.user.is_valid.update_at.app_error", nil, "user_id="+u.Id)
	}

	if len(u.TeamId) != 26 {
		return NewLocAppError("User.IsValid", "model.user.is_valid.team_id.app_error", nil, "")
	}

	if !IsValidUsername(u.Username) {
		return NewLocAppError("User.IsValid", "model.user.is_valid.username.app_error", nil, "user_id="+u.Id)
	}

	if len(u.Email) > 128 || len(u.Email) == 0 {
		return NewLocAppError("User.IsValid", "model.user.is_valid.email.app_error", nil, "user_id="+u.Id)
	}

	if utf8.RuneCountInString(u.Nickname) > 64 {
		return NewLocAppError("User.IsValid", "model.user.is_valid.nickname.app_error", nil, "user_id="+u.Id)
	}

	if utf8.RuneCountInString(u.FirstName) > 64 {
		return NewLocAppError("User.IsValid", "model.user.is_valid.first_name.app_error", nil, "user_id="+u.Id)
	}

	if utf8.RuneCountInString(u.LastName) > 64 {
		return NewLocAppError("User.IsValid", "model.user.is_valid.last_name.app_error", nil, "user_id="+u.Id)
	}

	if len(u.Password) > 128 {
		return NewLocAppError("User.IsValid", "model.user.is_valid.pwd.app_error", nil, "user_id="+u.Id)
	}

	if len(u.AuthData) > 128 {
		return NewLocAppError("User.IsValid", "model.user.is_valid.auth_data.app_error", nil, "user_id="+u.Id)
	}

	if len(u.AuthData) > 0 && len(u.AuthService) == 0 {
		return NewLocAppError("User.IsValid", "model.user.is_valid.auth_data_type.app_error", nil, "user_id="+u.Id)
	}

	if len(u.Password) > 0 && len(u.AuthData) > 0 {
		return NewLocAppError("User.IsValid", "model.user.is_valid.auth_data_pwd.app_error", nil, "user_id="+u.Id)
	}

	if len(u.ThemeProps) > 2000 {
		return NewLocAppError("User.IsValid", "model.user.is_valid.theme.app_error", nil, "user_id="+u.Id)
	}

	return nil
}
开发者ID:ZBoxApp,项目名称:platform,代码行数:62,代码来源:user.go


注:本文中的unicode/utf8.RuneCountInString函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。