The string type in Go language is string
, which is a character sequence of the Unicode character set. Strings in Go are immutable, which means that once a string is created, its value cannot be changed. Strings cannot be assigned to nil
, but can be assigned to the empty string ""
.
In Go, there are many ways to create strings.
Use double quotes to create a string directly, for example:
str := "Hello, World!"
Backticks are used to create multi-line string constants, for example:
str := `Hello, World!`
You can use escape characters\
Add a character to create a string, for example:
str := "Hello, \"World!\""
Use the plus sign to concatenate multiple strings to create a new String, for example:
str1 := "Hello, " str2 := "World!" str := str1 + str2
You can use the fmt.Sprintf()
function to generate a new string , for example:
str := fmt.Sprintf("Hello, %s!", "World")
There are many string operations in Go language, such as obtaining string length, string concatenation, string splitting, finding substrings, replacing substrings, converting to uppercase/lowercase, etc.
To obtain the string length, you can use the built-in function len()
, for example:
str := "Hello, World!" length := len(str)
String concatenation can use the
operator or fmt.Sprintf()
function, for example:
str1 := "Hello, " str2 := "World!" str3 := str1 + str2 str4 := fmt.Sprintf("%s%s", str1, str2)
You can use the strings.Split()
function to split strings, for example:
str := "apple,banana,orange" slice := strings.Split(str, ",")
You can find substrings Use the strings.Index()
function, for example:
str := "Hello, World!" index := strings.Index(str, "World")
To replace a substring, you can use the strings.Replace()
function, for example:
str := "Hello, World!" newStr := strings.Replace(str, "World", "Golang", -1)
To convert to uppercase/lowercase, you can use the strings.ToUpper()
and strings.ToLower()
functions, for example:
str := "Hello, World!" upperStr := strings.ToUpper(str) lowerStr := strings.ToLower(str)
Generally speaking, Go language strings The operation is relatively simple and easy to understand, and it is widely used.
The above is the detailed content of How to write golang string. For more information, please follow other related articles on the PHP Chinese website!