go strings包_Go中的Strings包简介

go strings包

介绍 (Introduction)

Go’s string package has several functions available to work with the string data type. These functions let us easily modify and manipulate strings. We can think of functions as being actions that we perform on elements of our code. Built-in functions are those that are defined in the Go programming language and are readily available for us to use.

Go的string包具有几个可用于字符串数据类型的功能 。 这些功能使我们可以轻松地修改和操作字符串。 我们可以将函数视为对代码元素执行的操作。 内置函数是用Go编程语言定义的函数,可供我们随时使用。

In this tutorial, we’ll review several different functions that we can use to work with strings in Go.

在本教程中,我们将回顾几个可用于在Go中处理字符串的函数。

使字符串大写和小写 (Making Strings Uppercase and Lowercase)

The functions strings.ToUpper and strings.ToLower will return a string with all the letters of an original string converted to uppercase or lowercase letters. Because strings are immutable data types, the returned string will be a new string. Any characters in the string that are not letters will not be changed.

函数strings.ToUpperstrings.ToLower将返回一个字符串,其中原始字符串的所有字母都转换为大写或小写字母。 因为字符串是不可变的数据类型,所以返回的字符串将是新的字符串。 字符串中任何非字母的字符都不会更改。

To convert the string "Sammy Shark" to be all uppercase, you would use the strings.ToUpper function:

要将字符串"Sammy Shark"转换为全部大写,可以使用strings.ToUpper函数:

ss := "Sammy Shark"
fmt.Println(strings.ToUpper(ss))

   
   
Output
SAMMY SHARK

To convert to lowercase:

转换为小写:

fmt.Println(strings.ToLower(ss))

   
   
Output
sammy shark

Since you are using the strings package, you first need to import it into a program. To convert the string to uppercase and lowercase the entire program would be as follows:

由于您正在使用strings包,因此首先需要将其导入程序。 要将字符串转换为大写和小写,整个程序如下:

package main

import (
    "fmt"
    "strings"
)

func main() {
    ss := "Sammy Shark"
    fmt.Println(strings.ToUpper(ss))
    fmt.Println(strings.ToLower(ss))
}

The strings.ToUpper and strings.ToLower functions make it easier to evaluate and compare strings by making case consistent throughout. For example, if a user writes their name all lowercase, we can still determine whether their name is in our database by checking it against an all uppercase version.

strings.ToUpperstrings.ToLower函数通过使大小写一致来strings.ToLower评估和比较字符串的过程。 例如,如果用户将其姓名全写为小写,则仍然可以通过将其姓名与全大写字母进行比较来确定他们的姓名是否在我们的数据库中。

字符串搜索功能 (String Search Functions)

The strings package has a number of functions that help determine if a string contains a specific sequence of characters.

strings包具有许多有助于确定字符串是否包含特定字符序列的功能。

FunctionUse
strings.HasPrefixSearches the string from the beginning
strings.HasSuffixSearches the string from the end
strings.ContainsSearches anywhere in the string
strings.CountCounts how many times the string appears
功能
strings.HasPrefix 从头开始搜索字符串
strings.HasSuffix 从末尾搜索字符串
strings.Contains 在字符串中的任何地方搜索
strings.Count 计算字符串出现的次数

The strings.HasPrefix and strings.HasSuffix allow you to check to see if a string starts or ends with a specific set of characters.

strings.HasPrefixstrings.HasSuffix允许您检查字符串是否以一组特定字符开头或结尾。

For example, to check to see if the string "Sammy Shark" starts with Sammy and ends with Shark:

例如,检查字符串"Sammy Shark"Sammy开头并以Shark结尾:

ss := "Sammy Shark"
fmt.Println(strings.HasPrefix(ss, "Sammy"))
fmt.Println(strings.HasSuffix(ss, "Shark"))

   
   
Output
true true

You would use the strings.Contains function to check if "Sammy Shark" contains the sequence Sh:

您将使用strings.Contains函数来检查"Sammy Shark"包含序列Sh

fmt.Println(strings.Contains(ss, "Sh"))

   
   
Output
true

Finally, to see how many times the letter S appears in the phrase Sammy Shark:

最后,看看字母S在短语Sammy Shark出现了多少次:

fmt.Println(strings.Count(ss, "S"))

   
   
Output
2

Note: All strings in Go are case sensitive. This means that Sammy is not the same as sammy.

注意: Go中的所有字符串均区分大小写。 这意味着, Sammy是不一样的sammy

Using a lowercase s to get a count from Sammy Shark is not the same as using uppercase S:

使用小写字母sSammy Shark获取计数与使用大写字母S

fmt.Println(strings.Count(ss, "s"))

   
   
Output
0

Because S is different than s, the count returned will be 0.

因为Ss不同,所以返回的计数将为0

String functions are useful when you want to compare or search strings in your program.

当您想在程序中比较或搜索字符串时,字符串函数很有用。

确定字符串长度 (Determining String Length)

The built-in function len() returns the number of characters in a string. This function is useful for when you need to enforce minimum or maximum password lengths, or to truncate larger strings to be within certain limits for use as abbreviations.

内置函数len()返回字符串中的字符数。 当您需要强制使用最小或最大密码长度,或将较大的字符串截断为特定的限制以用作缩写时,此功能很有用。

To demonstrate this function, we’ll find the length of a sentence-long string:

为了演示此功能,我们将找到一个长句子字符串的长度:

import (
    "fmt"
    "strings"
)

func main() {
        openSource := "Sammy contributes to open source."
        fmt.Println(len(openSource))
}

   
   
Output
33

We set the variable openSource equal to the string "Sammy contributes to open source." and then passed that variable to the len() function with len(openSource). Finally we passed the function into the fmt.Println() function so that we could see the program’s output on the screen..

我们将变量openSource设置为等于字符串"Sammy contributes to open source." 然后使用len(openSource)将该变量传递给len()函数。 最后,我们将该函数传递给fmt.Println()函数,以便我们可以在屏幕上看到程序的输出。

Keep in mind that the len() function will count any character bound by double quotation marks—including letters, numbers, whitespace characters, and symbols.

请记住, len()函数将计算由双引号引起的任何字符,包括字母,数字,空格字符和符号。

字符串操作的功能 (Functions for String Manipulation)

The strings.Join, strings.Split, and strings.ReplaceAll functions are a few additional ways to manipulate strings in Go.

strings.Joinstrings.Splitstrings.ReplaceAll函数是在Go中处理字符串的其他几种方法。

The strings.Join function is useful for combining a slice of strings into a new single string.

strings.Join函数对于将字符串的一部分组合为新的单个字符串很有用。

To create a comma-separated string from a slice of strings, we would use this function as per the following:

要从一片字符串中创建一个逗号分隔的字符串,我们将按照以下方式使用此函数:

fmt.Println(strings.Join([]string{"sharks", "crustaceans", "plankton"}, ","))

   
   
Output
sharks,crustaceans,plankton

If we want to add a comma and a space between string values in our new string, we can simply rewrite our expression with a whitespace after the comma: strings.Join([]string{"sharks", "crustaceans", "plankton"}, ", ").

如果要在新字符串中的字符串值之间添加逗号和空格,则可以简单地在逗号后用空格重写表达式: strings.Join([]string{"sharks", "crustaceans", "plankton"}, ", ")

Just as we can join strings together, we can also split strings up. To do this, we can use the strings.Split function and split on the spaces:

正如我们可以将字符串连接在一起一样,我们也可以拆分字符串。 为此,我们可以使用strings.Split函数并在空格处进行分割:

balloon := "Sammy has a balloon."
s := strings.Split(balloon, " ")
fmt.Println(s)

   
   
Output
[Sammy has a balloon]

The output is a slice of strings. Since strings.Println was used, it is hard to tell what the output is by looking at it. To see that it is indeed a slice of strings, use the fmt.Printf function with the %q verb to quote the strings:

输出是字符串的一部分。 由于使用了strings.Println ,因此很难通过查看来判断输出是什么。 要查看它确实是字符串的一部分,请使用带有%q动词的fmt.Printf函数对字符串加引号:

fmt.Printf("%q", s)

   
   
Output
["Sammy" "has" "a" "balloon."]

Another useful function in addition to strings.Split is strings.Fields. The difference is that strings.Fields will ignore all whitespace, and will only split out the actual fields in a string:

除了strings.Split之外,另一个有用的功能是strings.Fields 。 不同之处在于strings.Fields将忽略所有空格,并且只会将字符串中的实际fields分开:

data := "  username password     email  date"
fields := strings.Fields(data)
fmt.Printf("%q", fields)

   
   
Output
["username" "password" "email" "date"]

The strings.ReplaceAll function can take an original string and return an updated string with some replacement.

strings.ReplaceAll函数可以采用原始字符串,并返回更新后的字符串并进行替换。

Let’s say that the balloon that Sammy had is lost. Since Sammy no longer has this balloon, we would change the substring "has" from the original string balloon to "had" in a new string:

假设Sammy拥有的气球丢了。 由于Sammy不再具有此气球,因此我们将新字符串中的子字符串"has"从原始字符串balloon更改为"had"

fmt.Println(strings.ReplaceAll(balloon, "has", "had"))

Within the parentheses, first is balloon the variable that stores the original string; the second substring "has" is what we would want to replace, and the third substring "had" is what we would replace that second substring with. Our output would look like this when we incorporate this into a program:

在括号内,第一个是balloon ,用于存储原始字符串的变量。 第二个子字符串"has"是我们要替换的东西,第三个子字符串"had"是我们要替换第二个子字符串的东西。 将其合并到程序中后,输出将如下所示:


   
   
Output
Sammy had a balloon.

Using the string function strings.Join, strings.Split, and strings.ReplaceAll will provide you with greater control to manipulate strings in Go.

使用字符串函数strings.Joinstrings.Splitstrings.ReplaceAll将为您提供更大的控制权,以便在Go中操作字符串。

结论 (Conclusion)

This tutorial went through some of the common string package functions for the string data type that you can use to work with and manipulate strings in your Go programs.

本教程介绍了一些用于字符串数据类型的常见字符串包函数,您可以使用这些函数在Go程序中使用和操作字符串。

You can learn more about other data types in Understanding Data Types and read more about strings in An Introduction to Working with Strings.

您可以在“ 了解数据类型”了解更多有关其他数据类型的信息,并在“使用字符串简介”中阅读有关字符串的更多信息。

翻译自: https://www.digitalocean.com/community/tutorials/an-introduction-to-the-strings-package-in-go

go strings包

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值