Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




GO - STRINGS


A String is a collection of letters/alphabets. It can be a word or a sentence.


The 'Data Type' for String is 'string'.


Declaring a String with Double Quotes ("")


When Go finds data inside Double Quotes (""). It creates a String type variable for that value.


var x = "Hello World"

Example :



package main
import "fmt"
    
func main() {   
    var x = "Hello World"
    fmt.Println(x)
    }
}


Output :



 Hello World

And that's all! You have a String in place.


Well! There are other ways using which you can create a string. They are listed below :


Declaring a String with ':='


x := "Hello World"

Example :



package main
import "fmt"
    
func main() {   
    x := "Hello World"
    fmt.Println(x)
}


Output :



 Hello World

Declaring a String with string data type


var x string = "Hello World"

Example :



package main
import "fmt"
    
func main() {   
    var x string = "Hello World"
    fmt.Println(x)
}	


Output :



 Hello World

Now, what if, you want a paragraph, separated by lines, to be assigned to a variable.


i.e. Let's say, you want to assign the below paragraph to a variable.


"In a huge pond,
there lived many fish.
They were arrogant
And never listened to anyone."

In such cases, you can use backticks (``).


Declaring a multiline String with backticks (``)


Declaring a multiline String with backticks (``) :


Example :



package main
import "fmt"
    
func main() {
        
var str = `In a huge pond, 
there lived many fish.
They were arrogant 
And never listened to anyone.`
    
fmt.Println(str)     	
           
}	


Output :



 In a huge pond,
 there lived many fish.
 They were arrogant
 And never listened to anyone.

Accessing the characters of a String


Example :



package main
import ("fmt")
    
func main() {
    
    x := "Hello"  
    y := x[1]
            
    fmt.Printf("%c \n", y)    
}	


Output :



 e

So, we have a string 'Hello',


x := "Hello"

And we have assigned 'Hello' to a variable 'x'.


java_Collections

Let us elaborate more, on how the String 'Hello' is stored in the variable 'x'.


java_Collections

So, just for the sake of understanding, you can assume the variable 'x' is divided into '5' parts to store 'Hello'.


Now, if you check from the front, the count starts from '0' and ends with '4'.


So, if we look at the next line in the code,


y := x[1]

We are trying to access the 2nd location,


java_Collections

So, 'x[1]' is referring to the 2nd location where 'e' is stored.


y = x[1]

And we have assigned 'e' to the variable 'y'.


java_Collections

Note : The square brackets '[]' are used with the string type variable to get the variable at that position(i.e. x[1] refers to the 2nd location that contains 'e').

Now, if you look at the print statement,


fmt.Printf("%c \n", y)

The value of 'y' is printed as output.


Output :



 e

Now, if you want to access a chunk of characters of a String, how can you do that?


Let us see it below.


Accessing a chunk of letters/characters from a String


Example :



package main
import "fmt"
    
func main() {   
    x := "Hello"
    y := x[1:4]
    fmt.Println(y)
}


Output :



 ell

So, we want to take the chunk of letters/characters from the String 'Hello' and store it into the variable 'y'.


And in the first line, we have stored 'Hello' inside 'x'.


x := "Hello"

java_Collections

Also, let us see the elaborated structure.


java_Collections

So, we want to take the chunk 'ell' from 'Hello'. And that happens in the next line.


y := x[1:4]

Just note, the position of 'e' from 'ell' is '1' and the position of the last 'l' from 'ell' is 3.


So, the statement, x[1,4] picks the value from position '1' till the position of the 'l' plus 1. i.e. The position of second 'l' is 3. We just add 1 to it.


So, the statement 'x[1:4]' simply refers, "Pick the chunk from position 1 to position (4-1)".


Note : The end position of 'x[1:4]' i.e. 4, might look a little weird. Looks like it should be '3' instead of '4'. But that is the way it is.

And 'ell' is assigned to the variable 'y'.


java_Collections

And in the next line, we have the print statement,


fmt.Println(y)

That prints the chunk of letters 'ell'.


Output :



 ell

Updating a portion of a String


Say we have a String "Hello" and we want to update it to "Hellboy".


Example :



package main
import "fmt"
    
func main() {   
    x := "Hello"
    y := x[:4] + "boy"
    fmt.Println(y)
}


Output :



 Hellboy

So, we have initialised the variable 'x' with the String 'Hello'.


x := "Hello"

java_Collections

Also, let us see the elaborated structure.


java_Collections

So, we have to replace the letter 'o' with 'boy'.


And as we can see, 'o' is in position '4'. So, we have used the statement,


y := x[:4] + "boy"

Where the value of position '4' gets replaced with 'b' followed 'o' and 'y'.


java_Collections

And finally print the value of 'y'.


fmt.Println(y)

In the above example, we have seen the '+' sign. And as we know, '+' is used for addition of two numbers.


Well! In Go, '+' can be used to join two Strings as well.


Concatenation of Strings


Say, we have two Strings, 'Hello' and 'World'. And we want to join/concatenate them into one String, 'HelloWorld'.


Let us solve it with the below example.


Example :



package main
import "fmt"
    
func main() {   
    x := "Hello"
    y := "World"
    z := x + y
    fmt.Println(z)
}


Output :



 HelloWorld

So, we have stored the String 'Hello' in 'x'.


x := "Hello"

And, stored the String 'World' in 'y'.


y := "World"

And used the '+' operator to join/concatenate 'Hello' and 'World'.


z := x + y

And store the concatenated value in 'z'.


java_Collections

So, '+' is not just used to add two numbers but '+' is also used to join/concatenate two Strings.


But we cannot use the '+' operator to join/concatenate a number and a String.


i.e. The below code will result into an error.


Example :



package main
import "fmt"
    
func main() {   
    x := 5
    y := "World"
    z := x + y
    fmt.Println(z)
}


Output :



 invalid operation: x + y (mismatched types int and string)

And as said it ended up with an error.


Now, what if, you wish to repeat a string a few number of times.


Repetition of a String using Repeat() Function


To repeat a String a few number of times, Go provides us with a Function called 'Repeat()' that repeats a string a few number of times.


Note : Function is a topic that will be discussed in a separate tutorial. For now, you can consider, a Function is something that is dedicated to do some specific work. Just like the work of Repeat() Function is to repeat a string a few times.

Let us see the below example.


Example :



package main
import "fmt"
import "strings"
    
func main() {   
           
    x := "Hello"
    y := strings.Repeat(x,3)
            
    fmt.Println(y)
}


Output :



 HelloHelloHello

So, if you see the output. The statement,


y := strings.Repeat(x,3)

Repeats the String 'Hello' three times.


Now, to use the Repeat() Function, you need to import 'strings'.


import "strings"

As the Function Repeat() is defined in 'strings'.


Then you use 'strings' to invoke the Repeat() Function, passing the actual string to be repeated (i.e. 'x := "Hello"') and number of times the string has to be repeated(i.e. '3').


y := strings.Repeat(x,3)

java_Collections

Next, let us see how to Iterate through the values of a String.


Iterate a String using for range loop


Example :



package main
import ("fmt")
    
func main() {
    x := "Hello"
    for i,letter := range x {
        fmt.Printf("Index : %d Value : %c \n", i, letter)
    }
}


Output :



 Index : 0 Value : H
 Index : 1 Value : e
 Index : 2 Value : l
 Index : 3 Value : l
 Index : 4 Value : o

So, each Iteration of 'for loop',


for i,letter := range x

The values are taken from the variable 'x', one by one and put in the variable 'y' and its corresponding indexes in the variable 'i'.


And values are printed at each Iteration.


fmt.Printf("Index : %d Value : %c \n", i, letter)


A detail explanation can be found in 'for range loop' topic


In the above example, we have printed the Index and its corresponding value. But, what if,we only wanted to print the value and not the index.


It can be achieved using the 'rune array'.


Iterate a String by converting to rune array


So, if we only want to print the value of the String and not the indexes, we can convert the string to 'rune array' and print its values.


Note : We will be having a separate tutorial on Array.

Example :



package main
import ("fmt")
	
func main() {
	x := "Hello"
		
	y := []rune(x)
		
	for i := 0; i < len(y); i++ {
		fmt.Printf("%c \n",y[i])
	}
}


Output :



 H
 e
 l
 l
 o

In the above example, all we have done os converted the String 'x',


x := "Hello"

To 'rune array',


y := []rune(x)

Whenever Go finds the 'rune' keyword with square bracket '[]' in front of it. It converts the String to 'rune array'.


Then we can use the 'for' loop to iterate and print the values of the String.


for i := 0; i < len(y); i++ {
	fmt.Printf("%c \n",y[i])
}

Now, let us look at a scenario, where you need to find out, if a particular letter or a chunk of letters is present in the string or not.


Checking if a substring is present in a String or not using Contains() function


Let us check, if the substring 'el' is present in the String 'Hello' or not.


To achieve it, Go provides a function called 'Contains()' that checks if a substring is present in a string or not.


Example :



package main
import "fmt"
import "strings"
	
func main() {
	
	x := "Hello"  
			
	if (strings.Contains(x,"el")) {
		fmt.Println("The sub-string, el is present in the String, Hello")
	} else {	
		fmt.Println("The sub-string, el is not present in the String, Hello")	
	} 
}


Output :



 The sub-string, el is present in the String, Hello

So, to check if the substring 'el' is present in the String 'Hello', we have used the 'Contains()'function with 'if' statement.


if (strings.Contains(x,"el"))

Note : The below topic 'String Formatting' is already explained in the tutorial 'Input & Output'.

String Formatting


Say, you have stored a number in a variable and you want to insert it in the middle of a String.


i.e. Say, you have two numbers '3' and '4' and you have added them and want to display the result in the following way,


  The added result of 3 and 4 is 7


Well! We can achieve it using String formatting.


String Formatting Operator '%'


Let us rewrite the above example using the String Formatting Operator '%'.


Example :



package main
import "fmt"
	
func main() {
	
	x := 3
	y := 4
	z := x + y
	fmt.Printf("The added value of %d and %d is %d \n", x, y, z)
}


Output :



 The added value of 3 and 4 is 7

Now, if you look at the output,


The added value of 3 and 4 is 7

You can see that '%d' is replaced with the actual values of the variables.


fmt.Printf("The added value of %d and %d is %d \n", x, y, z)

Similarly, we can use other placeholders for all types of data.


Below is the Array :





Type Description
d, i, u Decimal Number
x, X Hexadecimal Number
o Octal Number
f, F Floating Point Number
e, E Exponential Number
g, G Floating point/Exponential
c Single character
s, r, a String

Next, let us look at the Methods provided by Go to handle Strings more effectively.


Methods to handle Strings

  1. len()

    Used to return the length of a String.

    Example :


    package main
    import "fmt"
      
    func main() {
      
    	x := "Hello"
    	fmt.Println("The length of the String is :",len(x))
    }
    


    Output :



     The length of the String is : 5

You can check the individual methods by clicking on it.