Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Creating Strings
3.
String Length
4.
String Concatenation
5.
String Encoding and Unicode Code Points
6.
String Functions in Go
6.1.
Contains function
6.2.
Count function
6.3.
HasPrefix function 
6.4.
HasSuffix function
6.5.
Join function
6.6.
Repeat function
6.7.
Replace function
6.8.
Split function
6.9.
ToLower function
6.10.
ToUpper function
6.11.
Example
7.
FAQs
8.
Key takeaways
Last Updated: Mar 27, 2024

Go String

Author Shivam Verma
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Strings are widely used in every programming language. But In the Go language, strings are different from other languages like C, C++, JAVA, etc. A String in Go is a read-only slice of bytes. It is also known as a sequence of variable-width characters where each and every character follows the UTF-8 encoding.

The UTF-8 encoding is a variable-length encoding of Unicode code points as bytes. It is a very widely used encoding, as it is the standard encoding for different types of files like JSON strings, XML files, text files, etc.

In Go language, strings are created by enclosing a set of characters inside double quotes "".

Creating Strings

Generally, Strings are created by enclosing a set of characters inside double quotes "".

Here is an example in which we will create a simple string and then print it using the fmt.Println() function.

package main
import "fmt"
func main(){
    // Creating and initializing a string
    str:="Coding Ninjas."
    // printing the string
    fmt.Println("String is:",str)
}

Output

String is: Coding Ninjas.

Whenever string literals are encountered in our code, the compiler creates a String object with its value, in this case, "Coding Ninjas.".

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

String Length

In Go language, we can find the length of the string using two functions: len() and RuneCountInString(). The UTF-8 package provides the RuneCountInString() function that takes a string as an argument and returns the total number of runes presented in it. The len() function is used to find the number of bytes in the string.

Example

package main
import(
    "fmt"
    "unicode/utf8"
)
func main(){
    str:="Coding Ninjas"
    // string length using len() function
    len1:=len(str)
    // string length using RuneCountInString() function
    len2:=utf8.RuneCountInString(str)
    // printing the length of the string
    fmt.Println("string:", str)
    fmt.Println("Length of the string using len() function:", len1)
    fmt.Println("Length of the string using RuneCountInString() function:", len2)
}

Output

string: Coding Ninjas
Length of the string using len() function: 13
Length of the string using RuneCountInString() function: 13

String Concatenation

The process of adding multiple strings is known as string concatenation, and in Go, we can achieve that using the + operator.

Example 

package main
import(
"fmt"
)
func main(){
str1:="Coding"
str2:="Ninjas"
fmt.Println("Concatenated string:", str1 + " " + str2)
}

Output

Concatenated string: Coding Ninjas

String Encoding and Unicode Code Points

The Unicode standard specifies a unique value for each character in all kinds of human languages. The basic unit in Unicode is not character. It is code point instead. For most code points, each of them corresponds to a character, but each consists of several code points for a few characters.

In Go language, rune values represent the code points. The rune is a built-in alias of type int32.

There are several encoding methods in applications to represent code points, such as UTF-8 encoding and UTF-16 encoding. These days, the most popular encoding method is UTF-8 encoding. In Go language, all string constants are viewed as UTF-8 encoded. Illegal UTF-8 encoded string constants will make compilation fail at compile time. However, Go runtime can not prevent some strings from being illegally UTF-8 encoded at run time.

In UTF-8 encoding, we may store each code point value as one or more bytes (up to four bytes). For example, each English code point (corresponds to one English character) is stored as one byte; however, each Chinese code point (corresponds to one Chinese character) is stored as three bytes.

String Functions in Go

The standard library's "strings" package provides many useful string-related functions. Here is a list of important Golang string functions given below:

Contains function

We can search a particular string/character within a string using Contains(). It returns output either true or false.

Syntax

func Contains(str, substr string) bool

Count function

We use this function to count the number of non-overlapping instances of a string/text/character in the string.

Syntax

func Count(str, sep string) int

HasPrefix function 

We use this function to check whether string str begins with a specified string. It returns true if string str begins with pfx string. Otherwise, it returns false.

Syntax: 

func HasPrefix(str, pfx string) bool

HasSuffix function

We use this function to check whether string str ends with a specified string. It returns true if string str ends with sffx string. Otherwise, it returns false.

Syntax:

func HasSuffix(str, sffx string) bool

Join function

We use this function to concatenate the elements of string Slice to create a single string. The separator string sep specifies what to put between each slice element in the resulting string.

Syntax:

func Join(stringSlice []string, sep string) string

Repeat function

We use this function to repeat a string a specified number of times and return a new string consisting of cnt copies of the string str. The cnt must be greater or equal to 0.

Syntax:

func Repeat(str string, cnt int) string

Replace function

We use this function to replace some characters with other characters in a string. Here in the below syntax n specifies the number of characters we want to replace in string. If n is less than 0, there is no limit on the number of replacements.

Syntax:

func Replace(str, old, new string, n int) string

Split function

We use this function to break a string into a slice. This function splits the str string into all substrings separated by sep and returns a slice of the substrings between those separators.

Syntax:

func Split(str string, sep string) []string

ToLower function

We use this function to convert all characters of the str string to lowercase.

Syntax:

func ToLower(str string) string

ToUpper function

We use this function to convert all characters of the str string to uppercase.

Syntax:

func ToUpper(str string) string

Here is a Go program to demonstrate the above functions.

Example

package main
import(
    "fmt"
    str "strings"
)
func main(){
    fmt.Println("Contains function: ", str.Contains("ninjas", "nj"))
    fmt.Println("Count function: ", str.Count("ninjas", "n"))
    fmt.Println("HasPrefix function: ", str.HasPrefix("ninjas", "ni"))
    fmt.Println("HasSuffix function: ", str.HasSuffix("ninjas", "ass"))
    fmt.Println("Index function: ", str.Index("ninjas", "j"))
    fmt.Println("Join function: ", str.Join([]string{"Coding", "Ninjas"}, "-"))
    fmt.Println("Repeat function: ", str.Repeat("C", 4))
    fmt.Println("Replace function: ", str.Replace("ninjas", "n", "N", 2))
    fmt.Println("Split function: ", str.Split("H-E-L-L-O", "-"))
    fmt.Println("ToLower function: ", str.ToLower("CODING"))
    fmt.Println("ToUpper function: ", str.ToUpper("coding"))
}

Output

Contains function:  true
Count function:  2
HasPrefix function:  true
HasSuffix function:  false
Index function:  3
Join function:  Coding-Ninjas
Repeat function:  CCCC
Replace function:  NiNjas
Split function:  [H E L L O]
ToLower function:  coding
ToUpper function:  CODING

FAQs

  1. How do we concatenate strings in Golang?
    Ans: The easiest way of concatenating two or more strings in the Go language is by using the + operator. 
     
  2. How can we format a string without printing it?
    Ans: We can format a string without printing it using the fmt.Sprintf() function. It formats a string in the same way as fmt.Printf(), but returns the string instead of printing it.
     
  3. What are string literals in Golang?
    Ans: A string literal represents a string constant obtained from concatenating a sequence of characters. Go supports two styles of string literals: raw string literals and interpreted string literals.
    Raw string literals are character sequences between back quotes, as in `hi`.
    Interpreted string literals are character sequences between double quotes, as in "hello".

Key takeaways

In this article, We have extensively discussed the Strings in the Go programming language. We also discussed some string functions with the help of syntax and examples.

Check out this article - C++ String Concatenation

We hope that this blog has helped you enhance your knowledge regarding Go String and if you would like to learn more, check out our article on Go Loops. You can read other C language articles by clicking here. Do upvote our blog to help ninjas grow. Happy Coding!

Next article
Regex in Go
Live masterclass