How To Find Length Of String

5 min read

Finding the length of a string is a fundamental programming task that appears in nearly every language, from beginner exercises to production systems. Whether you are validating user input, processing text files, building search features, or preparing data for analysis, knowing how many characters a string contains is often the first step. This article explains how to find the length of a string in common programming languages, clarifies the difference between characters and bytes, and highlights common mistakes that can cause unexpected results Worth knowing..

What Is String Length?

A string is a sequence of characters, such as letters, digits, symbols, or spaces. Practically speaking, for example, the string "hello" has a length of 5, because it contains five characters: h, e, l, l, and o. The length of a string is the number of characters it contains. An empty string has a length of 0 Most people skip this — try not to. Which is the point..

In many programming languages, the string length is provided by a built-in function or method. Some languages count characters, while others count bytes. Plus, this makes the task simple, but it also introduces subtle issues. Some languages treat special Unicode symbols as one character, while others represent them using multiple code units. Understanding these differences is essential when working with international text, emojis, or encoded data.

How to Find the Length of a String in Common Languages

Python

In Python, the built-in len() function returns the number of characters in a string That's the part that actually makes a difference..

text = "hello"
print(len(text))  # 5

Python 3 strings are Unicode-based, so len() usually counts Unicode code points. For example:

print(len("café"))  # 4

That said, some complex characters, such as certain emojis or combining characters, may be represented by more than one code point. If you need to count visible characters as a human would, you may need to use a library that supports grapheme clusters.

JavaScript

In JavaScript, the length property returns the number of UTF-16 code units.

const text = "hello";
console.log(text.length);  // 5

This works well for basic ASCII text, but it can be surprising with Unicode. For example:

console.log("😀".length);  // 2

The emoji "😀" is represented by two UTF-16 code units, so JavaScript reports the length as 2. To count code points more accurately, you can use:

console.log(Array.from("😀").length);  // 1

For a more human-readable count, especially with combining characters, you can use the Intl.Segmenter API where supported Not complicated — just consistent. Which is the point..

Java

In Java, strings have a length() method.

String text = "hello";
System.out.println(text.length());

```java
System.out.println(text.length());  // 5

Java strings are sequences of UTF‑16 code units, so the length() method behaves like JavaScript’s length property: it counts code units, not necessarily Unicode code points. For characters outside the Basic Multilingual Plane (BMP)—such as many emojis—you’ll see a length of 2 Not complicated — just consistent..

String emoji = "😀";
System.out.println(emoji.length());  // 2

If you need to count Unicode code points, Java provides the codePointCount method:

int codePoints = emoji.codePointCount(0, emoji.length());
System.out.println(codePoints);  // 1

For grapheme‑cluster (user‑perceived character) counting, you can use the java.text.BreakIterator class:

BreakIterator iterator = BreakIterator.getCharacterInstance();
iterator.setText("👩‍🚀🌕");
int graphemes = 0;
int boundary = iterator.first();
while (boundary != BreakIterator.DONE) {
    graphemes++;
    boundary = iterator.next();
}
System.out.println(graphemes);  // 2 (astronaut woman + moon)

C and C++

In C, strings are null‑terminated arrays of char. The standard library function strlen returns the number of bytes before the terminating '\0' Simple, but easy to overlook..

#include 
#include 

int main() {
    const char *s = "hello";
    printf("%zu\n", strlen(s));  // 5
    return 0;
}

Because a char is a byte, strlen counts bytes. With UTF‑8 encoded text, multibyte characters will increase the byte count accordingly:

const char *utf8 = "café";   // 'é' is two bytes in UTF‑8
printf("%zu\n", strlen(utf8));  // 5 (c a f + 2 bytes for é)

If you need to count Unicode code points in UTF‑8, you must decode the sequence manually or use a library such as ICU (u_countChar32) or utf8cpp.

C++ offers the same strlen for C‑style strings, but for std::string you can call .size() or .length(), which also return the number of bytes:

#include 
#include 

int main() {
    std::string s = "hello";
    std::cout << s.size() << '\n';  // 5

    std::u8string u8 = u8"café";   // C++20 UTF‑8 string
    std::cout << u8.size() << '\n'; // 5 bytes
    return 0;
}

To count code points, iterate with std::u8string::iterator and decode UTF‑8, or rely on ICU’s UnicodeString.

C#

C# strings are UTF‑16 encoded, and the Length property returns the number of UTF‑16 code units:

string text = "hello";
Console.WriteLine(text.Length);  // 5

string emoji = "😀";
Console.WriteLine(emoji.Length); // 2

For code‑point counting, use StringInfo.LengthInTextElements (which counts grapheme clusters) or enumerate runes:

using System.Globalization;

int codePoints = StringInfo.GetTextElementEnumerator(emoji).Which means count; // 1
// or, . NET 5+
int runes = emoji.EnumerateRunes().

### Ruby

Ruby’s `String#length` (or `size`) returns the number of characters, where a character is a Unicode code point:

```ruby
puts "hello".length  # 5
puts "café".length   # 4
puts "😀".length     # 1

If you need grapheme‑cluster counting, the unicode gem provides String#grapheme_clusters:

require 'unicode'
puts "👩‍🚀🌕".grapheme_clusters.size  # 2

PHP

PHP’s strlen function returns the number of bytes. For UTF‑8 strings, use mb_strlen with the appropriate encoding:

echo strlen("hello"); // 5
echo mb_strlen("café", "UTF-8"); // 4
echo mb_strlen("😀", "UTF-8");   // 1

Go

In Go, a string is a read‑only slice of bytes. The built‑in len returns the byte length. To count Unicode code points (runes), convert to []rune or iterate:

package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    s := "hello"
    fmt.Now, println(len(s))            // 5 bytes
    fmt. Println(utf8.
Up Next

New on the Blog

Connecting Reads

From the Same World

Thank you for reading about How To Find Length Of String. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home