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


Golang strings.IndexFunc函数代码示例

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


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

示例1: main

func main() {
	fmt.Println(strings.Index("Hello, world!", "He"))  // 0: He가 맨 처음에 있으므로 0
	fmt.Println(strings.Index("Hello, world!", "wor")) // 7: wor가 8번째에 있으므로 7
	fmt.Println(strings.Index("Hello, world!", "ow"))  // -1: ow는 없으므로 -1

	fmt.Println(strings.IndexAny("Hello, world!", "eo")) // 1: e가 2번째에 있으므로 1
	fmt.Println(strings.IndexAny("Hello, world!", "f"))  // -1: f는 없으므로 -1

	var c byte
	c = 'd'
	fmt.Println(strings.IndexByte("Hello, world!", c)) // 11: d가 12번째에 있으므로 11
	c = 'f'
	fmt.Println(strings.IndexByte("Hello, world!", c)) // -1: f는 없으므로 -1

	var r rune
	r = '언'
	fmt.Println(strings.IndexRune("고 언어", r)) // 4: "언"이 시작되는 인덱스가 4

	f := func(r rune) bool {
		return unicode.Is(unicode.Hangul, r) // r이 한글 유니코드이면 true를 리턴
	}
	fmt.Println(strings.IndexFunc("Go 언어", f))       // 3: 한글이 4번째부터 시작하므로 3
	fmt.Println(strings.IndexFunc("Go Language", f)) // -1: 한글이 없으므로 -1

	fmt.Println(strings.LastIndex("Hello Hello Hello, world!", "Hello"))
	// 12: 마지막 Hello가 13번째에 있으므로 12

	fmt.Println(strings.LastIndexAny("Hello, world", "ol")) // 10: 마지막 l이 11번째에 있으므로 10

	fmt.Println(strings.LastIndexFunc("Go 언어 안녕", f)) // 13: 마지막 한글인 '녕'이 시작되는 인덱스가 13
}
开发者ID:jemoonkim,项目名称:golangbook,代码行数:31,代码来源:strings_Index.go

示例2: RemoveDateline

func RemoveDateline(text string) string {
	found := false
	for {
		brk := strings.IndexFunc(text, unicode.IsSpace)
		if brk < 0 {
			return text
		}

		word := text[0:brk]
		if word != strings.ToUpper(word) {
			if !found {
				return removeDatelineAlternative(text)
			} else {
				return text
			}
		}

		text = text[brk:]
		found = true

		nxt := strings.IndexFunc(text, isNotSkipped)
		if nxt < 0 {
			return ""
		}
		text = text[nxt:]
	}
}
开发者ID:michigan-com,项目名称:newsfetch,代码行数:27,代码来源:dateline.go

示例3: isSpell

func isSpell(str string) bool {
	//fmt.Printf("\tisSpell: %s\n", str)
	var pos = strings.IndexFunc(str, isVowel)
	if pos == -1 {
		return false
	}
	var next = strings.IndexFunc(str[pos+1:len(str)], isVowel)
	if next == -1 {
		return false
	}

	var end = pos + next + 2
	var first = str[pos:end]

	//fmt.Printf("\tfirst: %s\n", first)

	var posSecond = strings.LastIndex(str[end:len(str)], first)
	if posSecond == -1 {
		return isSpell(str[end-1 : len(str)])
	}

	var middle = str[end : end+posSecond]
	//fmt.Printf("\tmiddle: %s\n", middle)

	if len(middle) == 0 || strings.IndexFunc(middle, isVowel) == -1 {
		return isSpell(str[end-1 : len(str)])
	}

	return true
}
开发者ID:peter-popov,项目名称:gocodejam,代码行数:30,代码来源:c.go

示例4: IndexFunc

// IndexFunc returns the index into s of the first Unicode code point satisfying f(c)
// or -1 if none do
func IndexFunc(s string, f func(rune) bool) int {
	function := func(c rune) bool {
		return unicode.Is(unicode.Han, c)
	}

	fmt.Println(strings.IndexFunc("Hello, 世界", function))    // 7
	fmt.Println(strings.IndexFunc("Hello, world", function)) // -1
	return strings.IndexFunc(s, f)
}
开发者ID:upccup,项目名称:cuplearn,代码行数:11,代码来源:stringsTest.go

示例5: ExampleIndexFunc

func ExampleIndexFunc() {
	f := func(c rune) bool {
		return unicode.Is(unicode.Han, c)
	}
	fmt.Println(strings.IndexFunc("Hello, 世界", f))
	fmt.Println(strings.IndexFunc("Hello, world", f))
	// Output:
	// 7
	// -1
}
开发者ID:2thetop,项目名称:go,代码行数:10,代码来源:example_test.go

示例6: sweep

func (s *Server) sweep() {
	log.Printf("Performing sweep for old files")
	now := time.Now()

	accountsPath := filepath.Join(s.baseDirectory, "accounts")
	accountsDir, err := os.Open(accountsPath)
	if err != nil {
		log.Printf("Failed to open %s: %s", accountsPath, err)
		return
	}
	defer accountsDir.Close()

	ents, err := accountsDir.Readdir(0)
	if err != nil {
		log.Printf("Failed to read %s: %s", accountsPath, err)
		return
	}

	for _, ent := range ents {
		name := ent.Name()
		if len(name) != 64 || strings.IndexFunc(name, notLowercaseHex) != -1 {
			continue
		}

		filesPath := filepath.Join(accountsPath, name, "files")
		filesDir, err := os.Open(filesPath)
		if os.IsNotExist(err) {
			continue
		} else if err != nil {
			log.Printf("Failed to open %s: %s", filesPath, err)
			continue
		}

		filesEnts, err := filesDir.Readdir(0)
		if err == nil {
			for _, fileEnt := range filesEnts {
				name := fileEnt.Name()
				if len(name) > 0 && strings.IndexFunc(name, notLowercaseHex) == -1 {
					mtime := fileEnt.ModTime()
					if now.After(mtime) && now.Sub(mtime) > fileLifetime {
						if err := os.Remove(filepath.Join(filesPath, name)); err != nil {
							log.Printf("Failed to delete file: %s", err)
						}
					}
				}
			}
		} else {
			log.Printf("Failed to read %s: %s", filesPath, err)
		}

		filesDir.Close()
	}
}
开发者ID:carriercomm,项目名称:pond,代码行数:53,代码来源:server.go

示例7: checkName

func checkName(s string) error {
	if len(s) == 0 {
		return &ErrInvalidName{"not be empty"}
	}
	if strings.IndexFunc(s[:1], isRuneInvalidForFirstCharacter) != -1 {
		return &ErrInvalidName{"start with [A-Za-z_]"}
	}
	if strings.IndexFunc(s[1:], isRuneInvalidForOtherCharacters) != -1 {
		return &ErrInvalidName{"have second and remaining characters contain only [A-Za-z0-9_]"}
	}
	return nil
}
开发者ID:christian-blades-cb,项目名称:goavro,代码行数:12,代码来源:name.go

示例8: Parse

// Parse returns a Version struct filled with the epoch, version and revision
// specified in input. It verifies the version string as a whole, just like
// dpkg(1), and even returns roughly the same error messages.
func Parse(input string) (Version, error) {
	result := Version{}
	trimmed := strings.TrimSpace(input)
	if trimmed == "" {
		return result, fmt.Errorf("version string is empty")
	}

	if strings.IndexFunc(trimmed, unicode.IsSpace) != -1 {
		return result, fmt.Errorf("version string has embedded spaces")
	}

	colon := strings.Index(trimmed, ":")
	if colon != -1 {
		epoch, err := strconv.ParseInt(trimmed[:colon], 10, 64)
		if err != nil {
			return result, fmt.Errorf("epoch: %v", err)
		}
		if epoch < 0 {
			return result, fmt.Errorf("epoch in version is negative")
		}
		result.Epoch = uint(epoch)
	}

	result.Version = trimmed[colon+1:]
	if len(result.Version) == 0 {
		return result, fmt.Errorf("nothing after colon in version number")
	}
	if hyphen := strings.LastIndex(result.Version, "-"); hyphen != -1 {
		result.Revision = result.Version[hyphen+1:]
		result.Version = result.Version[:hyphen]
	}

	if len(result.Version) > 0 && !unicode.IsDigit(rune(result.Version[0])) {
		return result, fmt.Errorf("version number does not start with digit")
	}

	if strings.IndexFunc(result.Version, func(c rune) bool {
		return !cisdigit(c) && !cisalpha(c) && c != '.' && c != '-' && c != '+' && c != '~' && c != ':'
	}) != -1 {
		return result, fmt.Errorf("invalid character in version number")
	}

	if strings.IndexFunc(result.Revision, func(c rune) bool {
		return !cisdigit(c) && !cisalpha(c) && c != '.' && c != '+' && c != '~'
	}) != -1 {
		return result, fmt.Errorf("invalid character in revision number")
	}

	return result, nil
}
开发者ID:jamessan,项目名称:dcs,代码行数:53,代码来源:dpkgversion.go

示例9: maybeConvertMessagesToNewFormat

// maybeConvertMessagesToNewFormat scans the accounts directory for messages
// under the old naming scheme and updates them to use the new
// naming scheme that includes millisecond delivery time at the beginning.
func maybeConvertMessagesToNewFormat(baseDirectory string) error {
	accountsPath := filepath.Join(baseDirectory, "accounts")
	accountsDir, err := os.Open(accountsPath)
	if err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		return err
	}
	defer accountsDir.Close()

	accounts, err := accountsDir.Readdir(0)
	if err != nil {
		return err
	}

	for _, ent := range accounts {
		account := ent.Name()
		if len(account) != 64 || strings.IndexFunc(account, notLowercaseHex) != -1 {
			continue
		}

		accountPath := filepath.Join(accountsPath, account)
		accountDir, err := os.Open(accountPath)
		if err != nil {
			return err
		}
		ents, err := accountDir.Readdir(0)
		accountDir.Close()
		if err != nil {
			return err
		}

		for _, ent := range ents {
			name := ent.Name()
			if len(name) != 64 || strings.IndexFunc(name, notLowercaseHex) != -1 {
				continue
			}

			oldName := filepath.Join(accountPath, name)
			newName := filepath.Join(accountPath, timeToFilenamePrefix(ent.ModTime())+name)
			if err := os.Rename(oldName, newName); err != nil {
				return err
			}
		}
	}

	return nil
}
开发者ID:carriercomm,项目名称:pond,代码行数:52,代码来源:main.go

示例10: next

func (f *fields) next() string {
	notIsSpace := func(r rune) bool { return !unicode.IsSpace(r) }

	l := f.line[f.pos:]
	i := strings.IndexFunc(l, notIsSpace)
	if i < 0 {
		return ""
	}
	j := i + strings.IndexFunc(l[i:], unicode.IsSpace)
	if j < i {
		j = len(l)
	}
	f.pos += j
	return l[i:j]
}
开发者ID:jmptrader,项目名称:chess-1,代码行数:15,代码来源:uci.go

示例11: put

func put(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	q := r.URL.Query()
	plat := q.Get(":plat")
	cmd := q.Get(":cmd")
	ver := q.Get(":ver")
	if strings.IndexFunc(plat, badIdentRune) >= 0 ||
		strings.IndexFunc(cmd, badIdentRune) >= 0 ||
		strings.IndexFunc(ver, badVersionRune) >= 0 {
		http.Error(w, "bad character in path", 400)
		return
	}

	body, err := ioutil.ReadAll(http.MaxBytesReader(w, r.Body, 10e6))
	if err != nil && err.Error() == "http: request body too large" {
		http.Error(w, "too big", 413)
		return
	}
	if err != nil {
		log.Println(err)
		http.Error(w, "internal error", 500)
		return
	}

	var buf bytes.Buffer
	gz, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression)
	gz.Name = cmd + "-" + ver
	gz.Write(body)
	gz.Close()
	sha1, err := s3put(buf.Bytes(), gz.Name+".gz")
	if err != nil {
		log.Println(err)
		w.WriteHeader(500)
		return
	}

	_, err = db.Exec(`
		insert into release (plat, cmd, ver, sha1)
		values ($1, $2, $3, $4)
	`, plat, cmd, ver, sha1)
	if err != nil {
		log.Println(err)
		http.Error(w, "internal error", 500)
		return
	}
	w.WriteHeader(201)
	w.Write([]byte("created\n"))
}
开发者ID:uriel,项目名称:hk,代码行数:48,代码来源:main.go

示例12: moveDotRightWord

func moveDotRightWord(ed *Editor) {
	// Move to first space
	p := strings.IndexFunc(ed.line[ed.dot:], unicode.IsSpace)
	if p == -1 {
		ed.dot = len(ed.line)
		return
	}
	ed.dot += p
	// Move to first nonspace
	p = strings.IndexFunc(ed.line[ed.dot:], notSpace)
	if p == -1 {
		ed.dot = len(ed.line)
		return
	}
	ed.dot += p
}
开发者ID:yonglehou,项目名称:elvish,代码行数:16,代码来源:insert.go

示例13: htmlMessage

func htmlMessage(line weechat.LineData) template.HTML {
	if !strings.Contains(line.Message, "://") {
		// fast path.
		return template.HTML(template.HTMLEscapeString(line.Message))
	}
	buf := new(bytes.Buffer)
	for msg := line.Message; len(msg) > 0; {
		idx := strings.Index(msg, "://")
		switch {
		case idx >= 4 && msg[idx-4:idx] == "http":
			buf.WriteString(msg[:idx-4])
			msg = msg[idx-4:]
		case idx >= 5 && msg[idx-5:idx] == "https":
			buf.WriteString(msg[:idx-5])
			msg = msg[idx-5:]
		default:
			buf.WriteString(msg)
			msg = ""
			continue
		}
		space := strings.IndexFunc(msg, unicode.IsSpace)
		if space < 0 {
			space = len(msg)
		}
		u := msg[:space]
		msg = msg[space:]
		if _, err := url.Parse(u); err == nil {
			fmt.Fprintf(buf, `<a href="%s">%s</a>`, u, u)
		} else {
			buf.WriteString(u)
		}
	}
	return template.HTML(buf.String())
}
开发者ID:lyuyun,项目名称:loggregator,代码行数:34,代码来源:weechat.go

示例14: FirstWord

func FirstWord(s string) string {
	i := strings.IndexFunc(s, func(r rune) bool { return !unicode.IsLetter(r) })
	if i != -1 {
		return s[0:i]
	}
	return s
}
开发者ID:winglechen,项目名称:heroshi,代码行数:7,代码来源:worker.go

示例15: mustBuild

func mustBuild() (ver string) {
	tag := string(bytes.TrimSpace(mustCmd("git", "describe")))
	if tag[0] != 'v' {
		log.Fatal("bad tag name: ", tag)
	}
	ver = tag[1:]
	if strings.IndexFunc(ver, badVersionRune) >= 0 {
		log.Fatal("bad tag name: ", tag)
	}
	// TODO(kr): verify signature
	url := distURL + buildName + "-" + ver + "-" + buildPlat + ".json"
	if _, err := fetchBytes(url); err == nil {
		log.Fatal("already built: ", ver)
	}

	f, err := os.Create("relver.go")
	if err != nil {
		log.Fatal(err)
	}
	_, err = fmt.Fprintf(f, relverGo, ver)
	if err != nil {
		log.Fatal(err)
	}
	log.Println("go build -tags release -o " + buildName)
	cmd := exec.Command("go", "build", "-tags", "release", "-o", buildName)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err = cmd.Run()
	if err != nil {
		log.Fatal("go build -tags release: ", err)
	}
	return ver
}
开发者ID:Cardinala,项目名称:hk,代码行数:33,代码来源:build.go


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