title: Counting characters in golang string
body: <p>I am trying to count "characters" in go. That is, if a string contains one printable "glyph", or "composed character" (or what someone would ordinarily think of as a character), I want it to count 1. For example, the string "Hello, 世界", should count 11, since there are 11 characters, and a human would look at this and say there are 11 glyphs.</p>
  
  <p>utf8.RuneCountInString() works well in most cases, including ascii, accents, asian characters and even emojis. However, as I understand it runes correspond to code points, not characters. When I try to use basic emojis it works, but when I use emojis that have different skin tones, I get the wrong count: <a href="https://play.golang.org/p/aFIGsB6MsO" rel="noreferrer">https://play.golang.org/p/aFIGsB6MsO</a></p>
  
  <p>From what I read <a href="https://stackoverflow.com/questions/36569018/can-a-character-span-multiple-runes-in-go">here</a> and <a href="https://blog.golang.org/normalization" rel="noreferrer">here</a>  the following should work, but I still don't seem to be getting the right results (it over-counts):</p>
  
  <pre><code>func CountCharactersInString(str string) int {
      var ia norm.Iter
      ia.InitString(norm.NFC, str)
      nc := 0
      for !ia.Done() {
          nc = nc + 1
          ia.Next()
      }
      return nc
  }
  </code></pre>
  
  <p>This doesn't work either:</p>
  
  <pre><code>func GraphemeCountInString(str string) int {
      re := regexp.MustCompile("\\PM\\pM*|.")
      return len(re.FindAllString(str, -1))
  }
  </code></pre>
  
  <p>I am looking for something similar to this in Objective C:</p>
  
  <pre><code>+ (NSInteger)countCharactersInString:(NSString *) string {
      // --- Calculate the number of characters enterd by user and update character count label
      NSInteger count = 0;
      NSUInteger index = 0;
      while (index &lt; string.length) {
          NSRange range = [string rangeOfComposedCharacterSequenceAtIndex:index];
          count++;
          index += range.length;
      }
      return count;
   }
  </code></pre>