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 mainimport ("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包具有许多有助于确定字符串是否包含特定字符序列的功能。

Function Use
strings.HasPrefix Searches the string from the beginning
strings.HasSuffix Searches the string from the end
strings.Contains Searches anywhere in the string
strings.Count Counts 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包

go strings包_Go中的Strings包简介相关推荐

  1. go语言复数包_go语言学习之包和变量详解

    前言 本文主要介绍了关于go语言之包和变量的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧. 一.包的概念 包是go语言中不可缺少部分,在每个go源码的第一行进行定义,定义方 ...

  2. java中缺省包_Java 中的默认包问题

    起因 今天看< Java 编程思想>第六章的时候看到这样一句话: 一定要记住,相同目录下的所有不具有明确 package 声明的文件,都被视作是该目录下默认包的一部分. 以前没有深入了解过 ...

  3. python常用算法包_Python中常用的包--sklearn

    sklearn 线性回归LinearRegression()参数介绍 LinearRegression(fit_intercept=True,normalize=False,copy_X=True,n ...

  4. go语言复数包_Go语言中包的风格指南

    Go 语言也有自己的命名与代码组织规则.漂亮的代码,布局清晰.易读易懂,就像是设计严谨的 API 一样.拿到代码,用户首先看到和接触的就是布局.命名还有包的结构. 这篇文章不是为了给大家设立硬性的规定 ...

  5. msdb 数据库_如何检索有关存储在MSDB数据库中的SSIS包的信息

    msdb 数据库 介绍 (Introduction) Nowadays, most mid-size companies have implemented a Data Warehouse (DWH) ...

  6. JAVA 中的代码生成包 CGLIB (Code Generation Library)

    JAVA 中的代码生成包 CGLIB (Code Generation Library) CGLIB 是一个功能强大,高性能的代码生成包.它为没有实现接口的类提供代理,为 JDK 的动态代理提供了很好 ...

  7. 使用govendor灵活管理Go程序中的依赖包

    业务痛点 使用Go开发程序的过程中,为了方便开发,往往会引用很多标准库或者第三方的依赖包,第三方依赖包往往比标准库功能更全面更强大更接地气,那么如何管理众多的第三方依赖包呢?如何更新其版本?在不需要时 ...

  8. Oracle EBS R12 运行adadmin 安装中文语言包过程中意外中断后的处理

    介绍Oracle EBS R12 运行adadmin 安装中文语言包过程中意外中断后的处. Oracle EBS R12 运行adadmin 安装中文语言包过程中意外中断或关机后,重新开机,运行数据库 ...

  9. helm部署仓库中没有的包_Kubernetes的Helm软件包管理器简介

    helm部署仓库中没有的包 Before we dive into the Helm package manager, I'm going to explain some key concepts t ...

最新文章

  1. logcat --pid xx 查看某个进程的信息
  2. MySQL 自增ID
  3. [TJOI2013]最长上升子序列
  4. grpc通信原理_容器原理架构详解(全)
  5. LinkedList 使用巩固及图解
  6. JavaScript的正则表达式实现邮箱校验
  7. P1739表达式括号匹配
  8. SVN switch 用法详解
  9. Spring5参考指南:SpringAOP简介
  10. cocos2d-x开发之动作游戏实战--5
  11. MySQL系列(一) MySQL体系结构概述
  12. python模块导入_Python模块及其导入
  13. 扒网站:模板小偷 单页模板扒手
  14. 【英语学习】【WOTD】disbursement 释义/词源/示例
  15. C语言标准库<math.h>
  16. Homebrew 更换阿里云镜像源
  17. SharePoint 2007有性能问题? 先试试这篇.
  18. win11快捷键怎么使用 Windows11快捷键的使用方法
  19. python操作mysql时mysqldb和pymysql的安装和使用
  20. vs配置opencv

热门文章

  1. 医药行业数字化转型加速,上云势在必行!
  2. 围棋AI.续一.Sabaki+Leela Zero+Leelasabaki.2018年6月26日
  3. 【真人视频变卡通(Iphone手机)】
  4. 后端报错:Cannot read property ‘phone‘ of null
  5. CSS3眨眼效果(animation动画循环间的“暂停”、“延时”执行)
  6. tanx的3次方的不定积分:两种方法
  7. CS230(DeepLearning)Leture1的学习笔记
  8. 合同审查自动化-企业合同处理新模式
  9. 如何判断两个人合不合适?
  10. 【JSS-22双延时时间继电器】