Tuesday, December 18, 2018

Golang Example - 3 ways to check Length of a String with output

In this blog post, You will learn three programs
  • First program is Length or count of Character/bytes  of a String
  • Second program is  Length of runes in a String 
  • Third Program  is to find the length of string using pointer
String is sequence of characters which contains one or more words. In Golang, String is read only of arbitary bytes.String length is number of characters in a string, For example, Given input string is "Cloudhadoop", The length of the string is 11.

Example program  - Length or count of Character/bytes  of a String

In this program, Inbuilt len() function is used to calculate length of character of a string.
Here is a syntax of len function
func len(input Type) int
This function accept input parameter of type like array,slice,strings, channel
package main
import (
 "fmt"
)

func main() {
 str1 := "This is test program"
 fmt.Println(len(str1)) //11
}
Output is
20

Example program Length of runes in a String

Package unicode/utf8 provides RuneCountInString function to find out runes count of a string

Here is a Syntax of RuneCountInString function
func RuneCountInString(s string) (n int)
Here is a program to check runes count of a string using RuneCountInString function
package main

import (
 "fmt"
 "unicode/utf8"
)

func main() {
 str := "Cloudhadoop"
 fmt.Println(utf8.RuneCountInString(str)) // 11

}
output is
11 

Example program 3 length of a string using pointer

address of variable can be find using & ambersand symbole
lenght of String using pointer or address can be found using *(star) followed by variable
Here is an example checking string pointer length
package main

import (
 "fmt"
)

func main() {
 str := "cloudhadoop"
 address := &str
 fmt.Println(len(*address))

}
Output is
11

Related article


EmoticonEmoticon