Go Standard Library Cookbook
上QQ阅读APP看书,第一时间看更新

How it works...

The simplest form of how to split the string into words considers any whitespace as a separator. In detail, the whitespace is defined by the IsSpace function in the unicode package:

'\t', '\n', '\v', '\f', '\r', ' ', U+0085 (NEL), U+00A0 (NBSP). 

The Fields function of the strings package could be used to split the sentence by the whitespace chars as mentioned earlier. The steps 1 – 5 cover this first simple case.

If any other separator is needed, the Split function comes into play. Splitting by another separator is covered in steps 6 – 8. Just note that the whitespace in the string is omitted.

If you need a more complex function to decide whether to split the string at a given point, FieldsFunc could work for you. One of the function's argument is the function that consumes the rune of the given string and returns true if the string should split at that point.  This option is covered by steps 9 – 11.

The regular expression is the last option mentioned in the example. The Regexp structure of the regexp package contains the Split method, which works as you would expect. It splits the string in the place of the matching group. This approach is used in steps 12 – 14.