Go Program for String Copy

Go Program for String Copy

In Go programming, ‘=’ is used to copy string or copy substring and [start:end] syntax is used if only some of the characters (substring) needs to be copied.

Substring Copy

Gets the substring in string variable from start index to end index.

Str_variable[start_index:end_index]
package main                                                               	 
                                                                           	 
import "fmt"                                                               	 
                                                                           	 
func main() {                                                              	 
	var str1, str2 string                                                  	 
	// string copy operations                                              	 
	str1 = "codingpointer.com!"                                            	 
	fmt.Println(str1)                                                      	 
                                                                           	 
	// copy all data                                                       	 
	str2 = str1[0:len(str1)]                                               	 
	fmt.Println(str2)                                                      	 
                                                                           	 
	// copy first 4 characters                                             	 
	str2 = str1[:4]                                                        	 
	fmt.Println(str2)                                                      	 
                                                                           	 
	// copy characters from index 2 to 6                                   	 
	str2 = str1[2:6]                                                       	 
	fmt.Println(str2)                                                      	 
                                                                           	 
	// copy last four characters                                           	 
	str2 = str1[len(str1)-4:len(str1)]                                     	 
	fmt.Println(str2)                                                      	 
}
Output:
$ go build string-copy.go
$ ./string-copy
codingpointer.com!
codingpointer.com!
codi
ding
com!