Hello everyone, my name is Xie Wei, I am a programmer.

Since I changed my job, I haven’t had much energy to output. I still need to spend some time to summarize, otherwise I will be unfamiliar with Go.

The theme of this season’s series revolves around built-in libraries. If someone writes better code than you, they probably know more about the built-in libraries than you do.

Familiarity with the built-in libraries helps you write better code. If you’re not familiar with the built-in apis, you might want to implement them yourself.

Principle:

  • Familiar with built-in apis
  • 5. Add new knowledge
  • Make up for shortcomings

The outline

  • Guess what usage will be provided

    • Case conversion
      • My own idea: 26 lowercase letters, 26 uppercase letters
    • Whether prefix, suffix
      • The functions are named has, is
      • Your own train of thought
    • segmentation
    • conversion
    • contains
    • statistical
    • Remove specified characters
    • character
  • Basic usage

  • Learn to

    • The function name
      • is
      • has
      • can
      • should
      • ok
      • found
      • done
      • success
    • Plural: tests, testcases, tt
    • Anonymous fields
    • Anonymous structure
      • Defining global variables
      • Test data set: slice

Self – summed up usage

String is an important data type built in, and the processing of string is also a very important part of daily writing code.

With my own coding experience, let’s review.

You can only relate to yourself by reviewing the standard API

  • String cleanup
For example, crawlers often deal with the source code of web pages, and the strings obtained can be mixed with unnecessary strings, so it is necessary to clean the strings at this time. 1. Replace: Replace specified substrings or characters. 2. Remove Spaces: not the same as replaceCopy the code
  • contains
Contains: 1. Does the original string contain substrings? 2. Whether it starts with a substring, whether it ends with a substringCopy the code
  • segmentation
Splits the original string by the specified one or more characters, returning an array typeCopy the code
  • statistical
Strictly one of the inclusion relationshipsCopy the code
  • Case conversion
This feature is common, such as the common search function, where some systems are strictly case sensitive while others are not, or support fuzzy search, in which case the case conversion function is usefulCopy the code

In my humble opinion, the above usage covers most scenarios.

The specific usage of the corresponding function

  • String cleanup
func stringsClean(value string) string {
	newReplacer := strings.NewReplacer("\n".""."\t"."")
	newValue := newReplacer.Replace(value)
	return strings.TrimSpace(newValue)
}


Copy the code
  • contains

func stringsContains(value string, subString string) bool {
	return strings.Contains(value, subString)
}
Copy the code
  • segmentation
func stringsSplit(value string, splitString string) []string {
	return strings.Split(value, splitString)
}
Copy the code

The same type of usage:

  • strings.SplitN
  • strings.SplitAfterN
  • strings.Split
  • strings.SplitAfter

Why design other methods?

  • The need for partial segmentation

  • A requirement that is partitioned as required

  • statistical

func stringsCount(value string, subString string) int {
	return strings.Count(value, subString)
}
Copy the code

What are the problems with substring statistics?

  • Are the matching rules set differently and the results are different?
  • What about matching empty substrings?

For example: fivevev, veV is the result 1, or 2?

  • Case conversion

func stringsLowerOrUpper(value string, toLower bool) string {
	if toLower {
		return strings.ToLower(value)
	}
	return strings.ToUpper(value)
}

Copy the code

Will there be a question: how to deal with “numeric” string? How to handle special characters?

Answer: As-is output, processing only 26 English letters

Standard core function

contains

There are other include functions:

  • strings.Contains
  • strings.ContainsAny
  • strins.ContainsRune

Character and ASCII operations?

var charOne rune = 'a'

fmt.Print(string(charOne), "" , int(charOne))
>> a  97
Copy the code

statistical

The rabin-Karp algorithm is adopted.

  • When counting null characters, it is a string length value

segmentation

Here are two interesting functions:

  • Fields and FieldsFunc

How does it work?


func stringsFiled(value string) []string {
	return strings.Fields(value)
}

func main() {

	fields := stringsFiled("How can i become gopher ")
	for index, field := range fields {
		fmt.Println(index, field, len(field))
	}

}

>>
0 How 3
1 can 3
2 i 1
3 become 6
4 gopher 6
Copy the code

While FieldsFunc appears to split by Spaces, FieldsFunc splits by specified characters

Prefixes and suffixes

  • HasPrefix
  • HasSuffix

Note: Naming

Boolean types suggest these words

  • is
  • can
  • has
  • should
  • found
  • success
  • ok

replace

  • Replace Replace a single character
  • Replacer Multiple character replacement

Slice or array to string

  • Join

Remove the character

  • func Trim(s string, cutset string) string
  • func TrimFunc(s string, f func(rune) bool) string
  • func TrimLeft(s string, cutset string) string
  • func TrimLeftFunc(s string, f func(rune) bool) string
  • func TrimPrefix(s, prefix string) string
  • func TrimRight(s string, cutset string) string
  • func TrimRightFunc(s string, f func(rune) bool) string
  • func TrimSpace(s string) string
  • func TrimSuffix(s, suffix string) string

A common one is TrimSpace, which removes whitespace at the end of a string.

other

  • How to express the plural form?
1. Plural forms of direct words: testcasesforindex, testcase := range testcases{ } 2. Double character: for example ttfor index, t := range tt {

}


Copy the code
  • Anonymous structure

What are the uses?

Var globalVar struct {name string age int} globalvar. name ="xieWei"Globalvar. age = 20 2test = []struct{
    in string
    out string
}{
    {
        in: "1",
        out: "2",}}Copy the code
  • Something to learn from
- Function naming: it looks like you can read functions to know how to use them - an introduction to the APICopy the code

reference

  • strings
  • strings

The back-end engineer strategy In the first quarter iteration: space.bilibili.com/10056291/#/…