FAQ - Help and questions

Why does the length of the same string differ between Rust, Python, JavaScript, Java, C# and Go?

#porting#strings#unicodepublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Languages count different things. Rust and Go count UTF-8 bytes, Python counts code points, and JavaScript, Java and C# count UTF-16 code units. What a reader sees as one character can be several code points. When porting string code, decide whether you mean bytes, code points or user-visible characters.

Checked with rustc 1.93.0, unicode-segmentation 1.13.3, Python 3.13.7, Node.js v22.19.0, Go 1.26.5, OpenJDK 17.0.18, .NET SDK 10.0.302, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

The test string has an e followed by a combining acute accent (it displays as one letter), a face emoji, and the flag of India (two regional-indicator code points that display as one flag). It looks like three characters.

UnitRustPythonJavaScriptJavaC#Go
UTF-8 bytess.len(): 15len(s.encode()): 15Buffer.byteLength: 15getBytes(UTF_8).length: 15Encoding.UTF8.GetByteCount: 15len(s): 15
Code pointss.chars().count(): 5len(s): 5[...s].length: 5codePointCount: 5EnumerateRunes().Count(): 5utf8.RuneCountInString: 5
UTF-16 code unitsencode_utf16().count(): 88s.length: 8s.length(): 8s.Length: 8not built in
User-visible characters (grapheme clusters)the unicode-segmentation crate: 3needs a libraryIntl.Segmenter: 3needs BreakIterator or a library (not run)StringInfo.LengthInTextElements: 3needs a library

Every number in the table comes from running the code below. The default meaning of "length" is bytes in Rust and Go, code points in Python, and UTF-16 units in JavaScript, Java and C#. A port that keeps the word "length" but changes the unit changes behaviour for any text outside plain ASCII.

Rust (1.93.0, with unicode-segmentation 1.13.3):

src/main.rsrust
use unicode_segmentation::UnicodeSegmentation;

fn main() {
    // "e" + combining acute accent, a face emoji, and the flag of India (two regional-indicator letters)
    let s = "e\u{301}\u{1F600}\u{1F1EE}\u{1F1F3}";
    println!("UTF-8 bytes       : {}", s.len());
    println!("code points       : {}", s.chars().count());
    println!("UTF-16 code units : {}", s.encode_utf16().count());
    println!("graphemes         : {}", s.graphemes(true).count());
    // slicing is by byte offset and must land on a character boundary
    println!("{:?}", s.get(0..1));
    println!("{:?}", s.get(0..2));
    println!("{}", s.is_char_boundary(2));
    println!("{:?}", "héllo".char_indices().map(|(i, _)| i).collect::<Vec<_>>());
}
text
UTF-8 bytes       : 15
code points       : 5
UTF-16 code units : 8
graphemes         : 3
Some("e")
None
false
[0, 1, 3, 4, 5]

Slicing by byte range is allowed only on character boundaries: s.get(0..2) is None because byte 2 is inside the two-byte accent, and indexing with s[0..2] would panic. char_indices shows that é takes two bytes (offsets 1 to 3).

JavaScript (Node.js v22.19.0) gave 8 UTF-16 units, 5 code points, 15 UTF-8 bytes and 3 graphemes for the same string:

javascript
const s = "é\u{1F600}\u{1F1EE}\u{1F1F3}";
console.log("UTF-16 code units:", s.length);
console.log("code points      :", [...s].length);
console.log("UTF-8 bytes      :", Buffer.byteLength(s, "utf8"));
console.log("graphemes        :", [...new Intl.Segmenter().segment(s)].length);

Python (3.13.7), Go (1.26.5), Java (17.0.18) and C# (.NET 10.0.302) were run with the same string and printed the numbers in the table. Go, for example:

go
s := "é\U0001F600\U0001F1EE\U0001F1F3"
fmt.Println("len (UTF-8 bytes):", len(s))
fmt.Println("runes            :", utf8.RuneCountInString(s))
text
len (UTF-8 bytes): 15
runes            : 5

How to do it#

  1. For each use of length, len, substring, indexing or padding in the old code, write down what it was counting: storage size (bytes), a unit of the text (code points), or what the user sees.
  2. Pick the Rust API that counts the same unit: len() for bytes, chars().count() for code points, a grapheme library for visible characters.
  3. For limits that come from a database column or a protocol, count in the unit the other side uses (usually bytes).
  4. For truncation, cut at a character boundary: s.char_indices().nth(n) gives a safe offset, or build the shortened string from chars().take(n).
  5. For columns and alignment in text output, count display width, which is a fourth meaning not covered here; the width of an emoji or a Chinese character in a terminal is a rendering question.

Common mistakes#

  • Using s.len() as "number of characters" for user input checks such as maximum name length.
  • Indexing s[i]. It does not compile in Rust, because a str is not indexable by one integer; the missing feature is protecting you from the ambiguity above.
  • Reversing a string by code points. The combining accent then attaches to the wrong letter.

Why is a Rust char 4 bytes?#

A char is one Unicode scalar value (a code point other than the surrogate range), so it needs up to 21 bits and is stored in 4 bytes.

Does normalisation matter?#

Yes: é can be one code point or e plus an accent, and the two are not equal as bytes. Normalise before comparing if your data can contain both; this thread did not run a normalisation crate.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet