Other Common String Operations
Explore common string operations in Go such as searching for substrings, comparing strings, converting case, and trimming whitespace. Understand the time complexity of these operations and how to apply them to solve text manipulation problems effectively.
We'll cover the following...
Knowing the basic string operations such as finding the length, traversal, indexing, concatenation, slicing, and splitting is an important start. Knowing additional string operations will make you better prepared for a wider range of string algorithms. A problem may ask whether two strings are equal, whether one string starts with another, whether a smaller string appears inside a larger one, or how to form a new string from existing ones.
Searching
Searching refers to the operation of locating a character or a substring within a larger string. At a fundamental level, this is accomplished by scanning through the string and examining each position until the target is found or the end of the string is reached.
Checking for existence
The simplest form of search determines whether a substring exists anywhere within the string. In Go, this is done using strings.Contains.
strings.Contains returns true if the substring is found and false otherwise.
Finding the position
When the exact position of the first occurrence is needed, Go provides strings.Index, which returns the starting byte index of the substring. If the substring is not present, strings.Index returns -1.
Go does not provide a separate string search function that raises an exception when the substring is missing. Instead, strings.Index returns -1, and you can check that value to handle the missing-substring case explicitly.
When using strings.Index, the important choice is whether -1 should be ...