Find string in another string

suggest change

Find the position of a string within another string

Using strings.Index:

main.go

	s := "where hello is?"
	toFind := "hello"
	idx := strings.Index(s, toFind)
	fmt.Printf("'%s' is in s starting at position %d\n", toFind, idx)

	// when string is not found, result is -1
	idx = strings.Index(s, "not present")
	fmt.Printf("Index of non-existent substring is: %d\n", idx)

Output:

'hello' is in s starting at position 6
Index of non-existent substring is: -1

Find the position of string within another string starting from the end

Above we searched from the beginning of the string. We can also search from the end using strings.LastIndex:

main.go

	s := "hello and second hello"
	toFind := "hello"
	idx := strings.LastIndex(s, toFind)
	fmt.Printf("when searching from end, '%s' is in s at position %d\n", toFind, idx)

Output:

when searching from end, 'hello' is in s at position 17

Find all occurrences of a substring

Above, we only found the first occurrence of the substring. Here’s how to find all occurrences:

main.go

	s := "first is, second is, third is"
	toFind := "is"
	currStart := 0
	for {
		idx := strings.Index(s, toFind)
		if idx == -1 {
			break
		}
		fmt.Printf("found '%s' at position %d\n", toFind, currStart+idx)
		currStart += idx + len(toFind)
		s = s[idx+len(toFind):]
	}

Output:

found 'is' at position 6
found 'is' at position 17
found 'is' at position 27

Check if a string contains another string

Using strings.Contains:

main.go

	s := "is hello there?"
	toFind := "hello"
	if strings.Contains(s, toFind) {
		fmt.Printf("'%s' contains '%s'\n", s, toFind)
	} else {
		fmt.Printf("'%s' doesn't contain '%s'\n", s, toFind)
	}

Output:

'is hello there?' contains 'hello'

Check if a string starts with another string

Using strings.HasPrefix:

main.go

	s := "this is string"
	toFind := "this"
	if strings.HasPrefix(s, toFind) {
		fmt.Printf("'%s' starts with '%s'\n", s, toFind)
	} else {
		fmt.Printf("'%s' doesn't start with '%s'\n", s, toFind)
	}

Output:

'this is string' starts with 'this'

Check if a string ends with another string

Using strings.HasSuffix:

main.go

	s := "this is string"
	toFind := "string"
	if strings.HasSuffix(s, toFind) {
		fmt.Printf("'%s' ends with '%s'\n", s, toFind)
	} else {
		fmt.Printf("'%s' doesn't end with '%s'\n", s, toFind)
	}

Output:

'this is string' ends with 'string'

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents