{"id":1800,"date":"2020-03-25T14:32:36","date_gmt":"2020-03-25T14:32:36","guid":{"rendered":"https:\/\/golangbyexamples.com\/?p=1800"},"modified":"2020-03-29T10:26:11","modified_gmt":"2020-03-29T10:26:11","slug":"number-characters-string-golang","status":"publish","type":"post","link":"https:\/\/golangbyexamples.com\/number-characters-string-golang\/","title":{"rendered":"Number of Characters or length of a string in Go (Golang)"},"content":{"rendered":"\n

In golang string is a sequence of bytes. A string literal actually represents a UTF-8 sequence of bytes. In UTF-8, ASCII characters are single-byte corresponding to the first 128 Unicode characters. All other characters are between 1 -4 bytes. That is why it is not possible to get the exact length of the string using the built-in len<\/strong> function of go. It might work if the string only contains ASCII characters. But if the string contains Non-ASCII characters then it will give the correct output.<\/p>\n\n\n\n

 For example, see below the program and its output. \u00a3<\/strong> in the string below is a Non-ASCII character.<\/p>\n\n\n\n

package main\n\nimport \"fmt\"\n\nfunc main() {\n    sample := \"ab\u00a3c\"\n    for i := 0; i < 4; i++ {\n        fmt.Printf(\"%c\\n\", sample[i])\n    }\n    fmt.Printf(\"Length is %d\\n\", len(sample))\n}<\/code><\/pre>\n\n\n\n

Output:<\/strong><\/p>\n\n\n\n

a\nb\n\u00c2\n\u00a3\nLength is 5<\/code><\/pre>\n\n\n\n

As you might have noticed , it prints different characters than expected and length is also 5 instead of 4. Why is that? To answer please remember we said that a string is essentially a slice of bytes. Let's print that slice of bytes using<\/p>\n\n\n\n

sample := \"ab\u00a3c\"\nfmt.Println([]byte(sample))<\/code><\/pre>\n\n\n\n

Output will be<\/p>\n\n\n\n

[97 98 194 163 99]<\/code><\/pre>\n\n\n\n

This is the mapping of each of character to its byte sequence. As you can notice a<\/strong>, b<\/strong>, c<\/strong> take each 1 byte but \u00a3<\/strong> takes two bytes. That is why the length of the string is 5 and not 4<\/p>\n\n\n\n

a<\/td>97<\/td><\/tr>
b<\/td>98<\/td><\/tr>
\u00a3<\/td>194, 163<\/td><\/tr>
c<\/td>99<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n

There are two alternatives to get the correct length of a string<\/p>\n\n\n\n

  • Using rune data type . rune<\/strong> data type represents a Unicode point.  Once a string is converted to an array of rune<\/strong> then it is possible to get the correct length of a string.<\/li><\/ul>\n\n\n\n
    • Using range operator over the string and calculating the length. range operator iterates over the UTF-8 characters in a string.<\/li><\/ul>\n\n\n\n

      The below code illustrates the above two points.<\/p>\n\n\n\n

      package main\n\nimport \"fmt\"\n\nfunc main() {\n    sample := \"ab\u00a3c\"\n    \/\/Using rune\n    s := []rune(sample)\n    fmt.Println(len(s))\n    \n    \/\/Using range\n    len := 0\n    for range sample {\n        len++\n    }\n    fmt.Println(len)\n}<\/code><\/pre>\n\n\n\n

      Output:<\/strong><\/p>\n\n\n\n

      4\n4<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"

      In golang string is a sequence of bytes. A string literal actually represents a UTF-8 sequence of bytes. In UTF-8, ASCII characters are single-byte corresponding to the first 128 Unicode characters. All other…<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","footnotes":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false},"categories":[1],"tags":[],"class_list":["post-1800","post","type-post","status-publish","format-standard","hentry","category-tech"],"yoast_head":"\nNumber of Characters or length of a string in Go (Golang) - Welcome To Golang By Example<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/golangbyexamples.com\/number-characters-string-golang\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Number of Characters or length of a string in Go (Golang) - Welcome To Golang By Example\" \/>\n<meta property=\"og:description\" content=\"In golang string is a sequence of bytes. A string literal actually represents a UTF-8 sequence of bytes. In UTF-8, ASCII characters are single-byte corresponding to the first 128 Unicode characters. All other...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/golangbyexamples.com\/number-characters-string-golang\/\" \/>\n<meta property=\"og:site_name\" content=\"Welcome To Golang By Example\" \/>\n<meta property=\"article:published_time\" content=\"2020-03-25T14:32:36+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2020-03-29T10:26:11+00:00\" \/>\n<meta name=\"author\" content=\"admin\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"admin\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/golangbyexamples.com\/number-characters-string-golang\/\",\"url\":\"https:\/\/golangbyexamples.com\/number-characters-string-golang\/\",\"name\":\"Number of Characters or length of a string in Go (Golang) - Welcome To Golang By Example\",\"isPartOf\":{\"@id\":\"https:\/\/golangbyexamples.com\/#website\"},\"datePublished\":\"2020-03-25T14:32:36+00:00\",\"dateModified\":\"2020-03-29T10:26:11+00:00\",\"author\":{\"@id\":\"https:\/\/golangbyexamples.com\/#\/schema\/person\/8833ea7638dafd763cb1db6c0ca4576f\"},\"breadcrumb\":{\"@id\":\"https:\/\/golangbyexamples.com\/number-characters-string-golang\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/golangbyexamples.com\/number-characters-string-golang\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/golangbyexamples.com\/number-characters-string-golang\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/golangbyexamples.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Number of Characters or length of a string in Go (Golang)\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/golangbyexamples.com\/#website\",\"url\":\"https:\/\/golangbyexamples.com\/\",\"name\":\"Welcome To Golang By Example\",\"description\":\"\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/golangbyexamples.com\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/golangbyexamples.com\/#\/schema\/person\/8833ea7638dafd763cb1db6c0ca4576f\",\"name\":\"admin\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/golangbyexamples.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/?s=96&d=mm&r=g\",\"caption\":\"admin\"},\"url\":\"https:\/\/golangbyexamples.com\/author\/admin\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Number of Characters or length of a string in Go (Golang) - Welcome To Golang By Example","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/golangbyexamples.com\/number-characters-string-golang\/","og_locale":"en_US","og_type":"article","og_title":"Number of Characters or length of a string in Go (Golang) - Welcome To Golang By Example","og_description":"In golang string is a sequence of bytes. A string literal actually represents a UTF-8 sequence of bytes. In UTF-8, ASCII characters are single-byte corresponding to the first 128 Unicode characters. All other...","og_url":"https:\/\/golangbyexamples.com\/number-characters-string-golang\/","og_site_name":"Welcome To Golang By Example","article_published_time":"2020-03-25T14:32:36+00:00","article_modified_time":"2020-03-29T10:26:11+00:00","author":"admin","twitter_card":"summary_large_image","twitter_misc":{"Written by":"admin","Est. reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/golangbyexamples.com\/number-characters-string-golang\/","url":"https:\/\/golangbyexamples.com\/number-characters-string-golang\/","name":"Number of Characters or length of a string in Go (Golang) - Welcome To Golang By Example","isPartOf":{"@id":"https:\/\/golangbyexamples.com\/#website"},"datePublished":"2020-03-25T14:32:36+00:00","dateModified":"2020-03-29T10:26:11+00:00","author":{"@id":"https:\/\/golangbyexamples.com\/#\/schema\/person\/8833ea7638dafd763cb1db6c0ca4576f"},"breadcrumb":{"@id":"https:\/\/golangbyexamples.com\/number-characters-string-golang\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/golangbyexamples.com\/number-characters-string-golang\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/golangbyexamples.com\/number-characters-string-golang\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/golangbyexamples.com\/"},{"@type":"ListItem","position":2,"name":"Number of Characters or length of a string in Go (Golang)"}]},{"@type":"WebSite","@id":"https:\/\/golangbyexamples.com\/#website","url":"https:\/\/golangbyexamples.com\/","name":"Welcome To Golang By Example","description":"","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/golangbyexamples.com\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/golangbyexamples.com\/#\/schema\/person\/8833ea7638dafd763cb1db6c0ca4576f","name":"admin","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/golangbyexamples.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/?s=96&d=mm&r=g","caption":"admin"},"url":"https:\/\/golangbyexamples.com\/author\/admin\/"}]}},"jetpack_featured_media_url":"","jetpack_publicize_connections":[],"jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/paOs1b-t2","amp_validity":null,"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/golangbyexamples.com\/wp-json\/wp\/v2\/posts\/1800","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/golangbyexamples.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/golangbyexamples.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/golangbyexamples.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/golangbyexamples.com\/wp-json\/wp\/v2\/comments?post=1800"}],"version-history":[{"count":4,"href":"https:\/\/golangbyexamples.com\/wp-json\/wp\/v2\/posts\/1800\/revisions"}],"predecessor-version":[{"id":1900,"href":"https:\/\/golangbyexamples.com\/wp-json\/wp\/v2\/posts\/1800\/revisions\/1900"}],"wp:attachment":[{"href":"https:\/\/golangbyexamples.com\/wp-json\/wp\/v2\/media?parent=1800"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/golangbyexamples.com\/wp-json\/wp\/v2\/categories?post=1800"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/golangbyexamples.com\/wp-json\/wp\/v2\/tags?post=1800"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}