Find string in another string

suggest change

Find the position of a string within another string

Using strings.Index:

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)
'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:

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)
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:

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):]
}
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:

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)
}
'is hello there?' contains 'hello'

Check if a string starts with another string

Using strings.HasPrefix:

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)
}
'this is string' starts with 'this'

Check if a string ends with another string

Using strings.HasSuffix:

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)
}
'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