Strings and strconv Package
In this lesson, you'll study strings, strconv package, and the functions supported by them.
We'll cover the following...
- Prefixes and suffixes
- Testing whether a string contains a substring
- Indicating the index a substring or character in a string
- Replacing substring
- Counting occurrences of a substring
- Repeating a string
- Changing the case of a string
- Trimming a string
- Splitting a string
- Joining over a slice
- Reading from a string
- Conversion to and from a string
- Try it yourself
Strings are a basic data structure, and every language has a number of predefined functions for manipulating strings. In Go, these are gathered in a package, strings. We’ll discuss below some very useful functions one by one.
Prefixes and suffixes
HasPrefix tests whether the string s begins with a prefix prefix:
strings.HasPrefix(s, prefix string) bool
HasSuffix tests whether the string s ends with a suffix suffix:
strings.HasSuffix(s, suffix string) bool
The following program implements these functions:
As you can see in the above code, we declare a string str and initialize it with This is an example of a string at line 9. At line 11, we used the function HasPrefix to find prefix Th in string str. The function returns true because str does start with Th. Similarly, at line 14, we used the function HasSuffix to find the suffix ting in string str. The function returns false because str does not end with ting. This also illustrates the use of the escape character \ to output a literal " with \" , and the use of 2 substitutions in a format-string.
Testing whether a string contains a substring
The function Contains returns true if substr is within s:
strings.Contains(s, substr string) bool
Indicating the index a substring or character in a string
Index returns the index of the first instance of str in s, or -1 if str is not present in s:
strings.Index(s, str string) int
LastIndex returns the index of the last instance of str in s, or -1 if str is not present in s:
strings.LastIndex(s, str string) int
If ch is a non-ASCII character, use:
strings.IndexRune(s string, ch int) int.
The following program finds the index of the substrings in a string:
As you can see in the above code, we declare a string str and initialize it with Hi, I’m Marc, Hi. at line 8. At line 10, we find the index of the first occurrence of Marc ...