Golang基础-字符串

Strings

A string in Go is an immutable(不可变的) sequence of bytes, which don't necessarily have to represent characters.
double quotes("") 和 backticks(`)的区别:双引号里可能有特殊字符(Special characters),例如\t, \n等,不能换行。反引号,raw string literal,没有特殊字符,没有\代表转义这一说,可以换行。
Raw string literals use backticks (`) as their delimiter instead of double quotes and all characters in it are interpreted literally, meaning that there is no need to escape characters or newlines.

const daltons = `Joe
William
Jack
Averell`
`abc`
// same as "abc"

"\"" // regular string literal with 1 character: a double quote
// same as `"` a raw string literal with 1 character: a double quote

`\n
` // raw string literal with 3 character: a backslash, an 'n', and a newline
// same as "\\n\n"  a regular string literal with 3 characters: a backslash, an 'n', and a newline

"\t\n" // regular string literal with 2 characters: a tab and a newline
`\t\n`// raw string literal with 4 characters: two backslashes, a 't', and an 'n'

Special characters

Value Description
\a Alert or bell
\b Backspace
\\ Backslash
\t Horizontal tab
\n Line feed or newline
\f Form feed
\r Carriage return
\v Vertical tab
\` Single quote
\" Double quote

Strings Package

常用函数

func ToLower(s string) string
func ToUpper(s string) string

//Trim leading and trailing whitespace
func TrimSpace(s string) string

//Find the index of the first instance of a substring within a string
func Index(s, substr string) int

func Replace(s, old, new string, n int) string
func ReplaceAll(s, old, new string) string
func Split(s, sep string) []string

//测试字符串 s 是否以 suffix 结尾。
func HasSuffix(s, suffix string) bool

//Count the number of occurrences of a substring within a string
func Count(s, substr string) int

//Repeat returns a new string consisting of count copies of the string s.
//It panics if count is negative or if the result of (len(s) * count) overflows.
func Repeat(s string, count int) string
// strings.Repeat returns a string with a substring given as argument repeated many times
strings.Repeat("Go", 3)
// => "GoGoGo"

Exercise

package techpalace
import "strings"


// WelcomeMessage returns a welcome message for the customer.
func WelcomeMessage(customer string) string {
    return "Welcome to the Tech Palace, " + strings.ToUpper(customer)
}

// AddBorder adds a border to a welcome message.
func AddBorder(welcomeMsg string, numStarsPerLine int) string {
    return strings.Repeat("*", numStarsPerLine) + "\n" + welcomeMsg + "\n" + strings.Repeat("*", numStarsPerLine)
}

// CleanupMessage cleans up an old marketing message.
func CleanupMessage(oldMsg string) string {
    res := strings.ReplaceAll(oldMsg, "*", "")
    res = strings.TrimSpace(res)
    return res
}
posted @ 2023-02-18 15:19  roadwide  阅读(48)  评论(0编辑  收藏  举报