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


Golang strings.Count函数代码示例

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


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

示例1: TestWorkflow

// TestWorkflow runs certstrap in the normal workflow
// and traverses all commands
func TestWorkflow(t *testing.T) {
	os.RemoveAll(depotDir)
	defer os.RemoveAll(depotDir)

	stdout, stderr, err := run(binPath, "init", "--passphrase", passphrase, "--common-name", "CA")
	if stderr != "" || err != nil {
		t.Fatalf("Received unexpected error: %v, %v", stderr, err)
	}
	if strings.Count(stdout, "Created") != 2 {
		t.Fatalf("Received insufficient create: %v", stdout)
	}

	stdout, stderr, err = run(binPath, "request-cert", "--passphrase", passphrase, "--common-name", hostname)
	if stderr != "" || err != nil {
		t.Fatalf("Received unexpected error: %v, %v", stderr, err)
	}
	if strings.Count(stdout, "Created") != 2 {
		t.Fatalf("Received insufficient create: %v", stdout)
	}

	stdout, stderr, err = run(binPath, "sign", "--passphrase", passphrase, "--CA", "CA", hostname)
	if stderr != "" || err != nil {
		t.Fatalf("Received unexpected error: %v, %v", stderr, err)
	}
	if strings.Count(stdout, "Created") != 1 {
		t.Fatalf("Received insufficient create: %v", stdout)
	}

}
开发者ID:ArtemKulyabin,项目名称:certstrap,代码行数:31,代码来源:workflow_test.go

示例2: linesof

func (p *parser) linesof(offsetFrom int, offsetTo int) SourceRange {
	strFrom := string(p.source[:offsetFrom])
	posFrom := strings.Count(strFrom, "\n")
	strTo := string(p.source[:offsetTo])
	posTo := strings.Count(strTo, "\n")
	return SourceRange{posFrom, posTo}
}
开发者ID:adriamb,项目名称:gopad,代码行数:7,代码来源:block.go

示例3: CreateTable

func CreateTable(tbl PicklesTableArgument) string {
	Html := ""
	if len(tbl.HeaderRow) > 0 {
		Html += "<table>"
		for n, y := range tbl.DataRows {
			if n == 1 && y[0] == strings.Repeat("-", strings.Count(y[0], "")-1) {
				continue
			}
			if n == len(tbl.DataRows)-1 && y[0] == strings.Repeat("-", strings.Count(y[0], "")-1) {
				continue
			}
			//fmt.Printf("ligne %d grp[%s] chaine lue [%s] taille:[%d] chaine de tiret [%s]\n",n,y,y[0],strings.Count(y[0],""),strings.Repeat("-", strings.Count(y[0],"")))
			Html += "<tr>"
			for _, z := range y {
				if n == 0 {
					Html += fmt.Sprintf("<th>%s</th>", z)
				} else {
					Html += fmt.Sprintf("<td>%s</td>", z)
				}
			}
			Html += "</tr>"
			//fmt.Printf("TableArgument.DataRows[%d]: %v\n", n,y)
		}
		Html += "</table>"
		// debug log.Fatalf("Stop %s",Html)

	}
	return Html
}
开发者ID:StephaneTy-Pro,项目名称:Pickles2TesLink,代码行数:29,代码来源:Pickles2TestLink.go

示例4: findFiles

func findFiles(path string, depth int, skips []*regexp.Regexp) ([]string, error) {
	baseNumSeps := strings.Count(path, string(os.PathSeparator))
	var files []string
	err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			log.Debugf("filewalk: %s", err)
			return nil
		}
		if info.IsDir() {
			pathDepth := strings.Count(path, string(os.PathSeparator)) - baseNumSeps
			if pathDepth > depth {
				return filepath.SkipDir
			}
		}
		name := info.Name()
		isSkip := false
		for _, skip := range skips {
			if skip.MatchString(name) {
				isSkip = true
				break
			}
		}
		// log.Println(isSkip, name)
		if !isSkip {
			files = append(files, path)
		}
		if isSkip && info.IsDir() {
			return filepath.SkipDir
		}
		return nil
	})
	return files, err
}
开发者ID:gobuild-old,项目名称:gobuild3,代码行数:33,代码来源:pack.go

示例5: watchDirAndChildren

// Add dir and children (recursively) to watcher
func (this *gowatch) watchDirAndChildren(path string) error {
	if err := this.w.Watch(path); err != nil {
		return err
	}
	baseNumSeps := strings.Count(path, string(os.PathSeparator))
	return filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
		if info.IsDir() {
			base := info.Name()
			if base != "." && strings.HasPrefix(base, ".") { // ignore hidden dir
				return filepath.SkipDir
			}

			pathDepth := strings.Count(path, string(os.PathSeparator)) - baseNumSeps
			if pathDepth > this.Depth {
				return filepath.SkipDir
			}
			if *verbose {
				fmt.Println(">>> watch dir: ", path)
			}
			if err := this.w.Watch(path); err != nil {
				return err
			}
		}
		return nil
	})
}
开发者ID:nXqd,项目名称:fswatch,代码行数:27,代码来源:fswatch.go

示例6: main

func main() {
	args := ArgumentList(os.Args)
	if githubRepo := args.GetArgument("--github", ""); githubRepo != "" {
		if strings.Count(githubRepo, "/") != 1 {
			fmt.Fprintf(os.Stderr, "Invalid GitHub repo: %s\n", githubRepo)
			os.Exit(2)
		}
		pieces := strings.Split(githubRepo, "/")
		githubImport(pieces[0], pieces[1])

	} else if args.GetArgument("--be", "") != "" {
		beImport()
	} else {
		if strings.Count(githubRepo, "/") != 1 {
			fmt.Fprintf(os.Stderr, "Usage: %s --github user/repo\n", os.Args[0])
			fmt.Fprintf(os.Stderr, "       %s --be\n", os.Args[0])
			fmt.Fprintf(os.Stderr, `
Use this tool to import an external bug database into the local
issues/ directory.

Either "--github user/repo" is required to import GitHub issues,
from GitHub, or "--be" is required to import a local BugsEverywhere
database.
`)
			os.Exit(2)
		}
	}
}
开发者ID:Komosa,项目名称:bug,代码行数:28,代码来源:main.go

示例7: TestLogBacktraceAt

func TestLogBacktraceAt(t *testing.T) {
	setFlags()
	defer logging.swap(logging.newBuffers())
	// The peculiar style of this code simplifies line counting and maintenance of the
	// tracing block below.
	var infoLine string
	setTraceLocation := func(file string, line int, ok bool, delta int) {
		if !ok {
			t.Fatal("could not get file:line")
		}
		_, file = filepath.Split(file)
		infoLine = fmt.Sprintf("%s:%d", file, line+delta)
		err := logging.traceLocation.Set(infoLine)
		if err != nil {
			t.Fatal("error setting log_backtrace_at: ", err)
		}
	}
	{
		// Start of tracing block. These lines know about each other's relative position.
		_, file, line, ok := runtime.Caller(0)
		setTraceLocation(file, line, ok, +2) // Two lines between Caller and Info calls.
		Info("we want a stack trace here")
		logging.wait()
	}
	numAppearances := strings.Count(contents(infoLog), infoLine)
	numLines := strings.Count(contents(infoLog), "\n")
	if numAppearances < 1 || numLines < 3 {
		// Need both the expected lines and enough more lines. Since we assume we have
		// no knowledge of the stacktrace format or the actual code stack being called,
		// we can't check for a higher number of lines.
		t.Fatal("got no trace back; log is ", contents(infoLog))
	}
}
开发者ID:khellan,项目名称:glog,代码行数:33,代码来源:glog_test.go

示例8: Walk

func Walk(root string, level int, exclude ...string) (list []string) {
	visit := func(path string, f os.FileInfo, err error) error {
		if strings.HasPrefix(f.Name(), ".") && f.IsDir() {
			return filepath.SkipDir
		}
		for _, ex := range exclude {
			if strings.HasSuffix(path, ex) && f.IsDir() {
				return filepath.SkipDir
			}
		}
		if f.IsDir() {
			list = append(list, path)
		}
		return nil
	}
	filepath.Walk(root, visit)
	sort.Sort(Path(list))
	end := len(list)
	for i, v := range list {
		if strings.Count(v, "/")-strings.Count(root, "/") > level {
			end = i
			break
		}
	}
	list = list[0:end]
	return
}
开发者ID:qjpcpu,项目名称:watchman,代码行数:27,代码来源:dir_walker.go

示例9: TestBatchSizeOnDump

func TestBatchSizeOnDump(t *testing.T) {
	c, clean, err := aetest.NewContext()
	if err != nil {
		t.Fatal(err)
	}
	defer clean()

	for _, i := range []int{10, 20, 50, 99, 100, 101} {
		t.Logf("Testing %d entities ...", i)
		if err := createSampleEntities(c, i); err != nil {
			t.Fatal(err)
		}
		w := new(bytes.Buffer)
		err := Dump(c, w, &Options{Kind: "User", PrettyPrint: false})
		if err != nil {
			t.Fatal(err)
		}
		count := strings.Count(w.String(), "__key__")
		if count != i {
			t.Errorf("Unexpected number of __key__'s %d: expected %d", count, i)
		}
		// t.Logf(w.String())
		// Check if we have all keys
		for id := 1; id <= i; id++ {
			sep := fmt.Sprintf(`["User",%d]`, id)
			occ := strings.Count(w.String(), sep)
			if occ != 1 {
				t.Errorf("Unexpected ocorrences of entity id %d: %d, expected 1", id, occ)
			}
		}
	}
}
开发者ID:ronoaldo,项目名称:aetools,代码行数:32,代码来源:funcs_test.go

示例10: parseSerialString

func parseSerialString(input string) (*big.Int, error) {
	ret := &big.Int{}

	switch {
	case strings.Count(input, ":") > 0:
		serialBytes := certutil.ParseHexFormatted(input, ":")
		if serialBytes == nil {
			return nil, fmt.Errorf("error parsing serial %s", input)
		}
		ret.SetBytes(serialBytes)
	case strings.Count(input, "-") > 0:
		serialBytes := certutil.ParseHexFormatted(input, "-")
		if serialBytes == nil {
			return nil, fmt.Errorf("error parsing serial %s", input)
		}
		ret.SetBytes(serialBytes)
	default:
		var success bool
		ret, success = ret.SetString(input, 0)
		if !success {
			return nil, fmt.Errorf("error parsing serial %s", input)
		}
	}

	return ret, nil
}
开发者ID:quixoten,项目名称:vault,代码行数:26,代码来源:path_crls.go

示例11: parseNext

func (this *toml) parseNext() error {
	str, err := readln(this.r)

	if err != nil {
		return err
	}

	str = strings.TrimSpace(str)
	if str == "" {
		//blank line
		return nil
	}

	if strings.HasPrefix(str, "#") {
		// comment line
		return nil
	}

	if strings.HasPrefix(str, "[") {
		//change the key
		str = strings.TrimLeft(str, "[")
		str = strings.TrimRight(str, "]")
		// allways have a trailing dot
		this.key = fmt.Sprintf("%s.", str)
		return nil
	}

	//we are parsing a key value!
	tmp := strings.SplitN(str, "=", 2)
	if len(tmp) != 2 {
		return fmt.Errorf("Error on line: %s, no equals sign!", str)
	}
	key := strings.TrimSpace(tmp[0])
	value := strings.TrimSpace(tmp[1])

	if !strings.HasPrefix(value, "[") {
		//its not an array
		v, ok := toVal(value)
		if !ok {
			return fmt.Errorf("Error on line: %s, unable to parse value %s", str, value)
		}
		this.output.PutWithDot(fmt.Sprintf("%s%s", this.key, key), v)
		return nil
	}

	//ok parse the damn array

	//arrays can contain multiple lines
	// so we count the opening and closing brackets.
	for strings.Count(str, "[") != strings.Count(str, "]") {
		ln, err := readln(this.r)
		if err != nil {
			return err
		}
		str = fmt.Sprintf("%s %s", str, ln)
	}

	return nil

}
开发者ID:trendrr,项目名称:goshire,代码行数:60,代码来源:toml.go

示例12: generatePoem

// Generate a poem with the given number of strophes and lines per strophe.
func generatePoem(strophes int, linesPerStrophe int) {
	// Find a catchy title
	title := strings.Trim(strings.Title(niall.Talk()), ".,;:!?_")
	if strings.Count(title, " ") > 4 {
		words := strings.Split(title, " ")
		title = strings.Join(words[:4], " ")
	}
	// Generate an appropriate amount of dashes
	dashes := ""
	for i := 0; i < len(title); i++ {
		dashes += "-"
	}
	// Output the header
	fmt.Printf("\n%s\n%s\n\n", title, dashes)
	// Generate and output all the srophes
	var line string
	for reps := 0; reps < strophes; reps++ {
		for i := 0; i < linesPerStrophe; i++ {
			// Try to get more than just a few words, up to 5 times
			for i2 := 0; i2 < 5; i2++ {
				line = niall.Talk()
				if strings.Count(line, " ") >= 3 {
					break
				}
			}
			fmt.Println(line)
		}
		fmt.Println()
	}
}
开发者ID:xyproto,项目名称:niall,代码行数:31,代码来源:main.go

示例13: removeComments

func removeComments(line string) string {
	// ditch the comments (but keep quoted hashes)
	if strings.Contains(line, "#") {
		segmentsBetweenHashes := strings.Split(line, "#")
		quotesAreOpen := false
		var segmentsToKeep []string
		for _, segment := range segmentsBetweenHashes {
			if strings.Count(segment, "\"") == 1 || strings.Count(segment, "'") == 1 {
				if quotesAreOpen {
					quotesAreOpen = false
					segmentsToKeep = append(segmentsToKeep, segment)
				} else {
					quotesAreOpen = true
				}
			}

			if len(segmentsToKeep) == 0 || quotesAreOpen {
				segmentsToKeep = append(segmentsToKeep, segment)
			}
		}

		line = strings.Join(segmentsToKeep, "#")
	}
	return line
}
开发者ID:ansel1,项目名称:godotenv,代码行数:25,代码来源:godotenv.go

示例14: ExampleCount

func ExampleCount() {
	fmt.Println(strings.Count("cheese", "e"))
	fmt.Println(strings.Count("five", "")) // before & after each rune
	// Output:
	// 3
	// 5
}
开发者ID:kostyll,项目名称:gccpy,代码行数:7,代码来源:example_test.go

示例15: CheckPreconditions

func (target *Target) CheckPreconditions() error {
	if err := ValidPath(target.File, target.FileFormat, ""); err != nil {
		return err
	}

	if strings.Count(target.File, "*") > 0 {
		return fmt.Errorf(
			"File pattern for 'pull' cannot include any 'stars' *. Please specify direct and valid paths with file name!",
			"http://docs.phraseapp.com/developers/cli/configuration/#targets",
		)
	}

	duplicatedPlaceholders := []string{}
	for _, name := range []string{"<locale_name>", "<locale_code>", "<tag>"} {
		if strings.Count(target.File, name) > 1 {
			duplicatedPlaceholders = append(duplicatedPlaceholders, name)
		}
	}

	if len(duplicatedPlaceholders) > 0 {
		dups := strings.Join(duplicatedPlaceholders, ", ")
		return fmt.Errorf(fmt.Sprintf("%s can only occur once in a file pattern!", dups))
	}

	return nil
}
开发者ID:iilei,项目名称:phraseapp-client,代码行数:26,代码来源:pull.go


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