String Length Calculator
Use this free online String Length Calculator which counts the length of the string instantly. Either you can copy and paste your text in the text area above, or you can type your text. By clicking the Submit button the counter will display the number of characters and whitespace in your text.
What are String Functions?
In computer programming languages, string functions are used to manipulate a string or query information about a string. A basic example of a string function is the length (string) function. For example, length(«hello world») would return 11.
String length function returns the length of a string literal. A string literal is a sequence of characters surrounded by double quotation marks («).
Most programming languages that have a string datatype will have some string functions. There may be other low-level ways within each language that handle strings directly. In object-oriented languages, string functions are often implemented as properties and methods of string objects. In functional and list-based languages a string is represented as a list, therefore all list-manipulation procedures could be considered string functions. However such languages may also implement a subset of explicit string-specific functions.
Modern object-oriented languages, like C# and Java, have immutable strings and return a copy (in newly allocated dynamic memory) for a function that manipulates strings, while others, like C manipulates the original string unless the programmer copies data to a new string.
What is a String?
In programming, a string is any finite sequence of characters (i.e., letters, numerals, symbols, and punctuation marks).
A string is a contiguous sequence of symbols or values, such as a character string (a sequence of characters) or a binary digit string (a sequence of binary values). It is used to represent text rather than numbers. It consists of a set of characters that can also contain spaces and numbers.
A string is considered as a data type and is often implemented as an array data structure of bytes or words that stores a sequence of elements, typically characters, using some character encoding. A string may also denote more general arrays or other sequences (or list) data types and structures.
It is known as a string literal or an anonymous string when a string appears in source code.
A string is a finite sequence of symbols that are chosen from a set called an alphabet in formal languages.
Formal strings can have an arbitrary but finite length, but the length of strings in real languages is often constrained to an artificial maximum. There are two types of string datatypes: fixed-length strings and variable-length strings. Fixed-length strings have a fixed maximum length to be determined at compile-time and use the same amount of memory whether this maximum is needed or not. The length of variable-length strings is not arbitrarily fixed and can use varying amounts of memory depending on the actual requirements at run time. In modern programming languages, most strings are variable-length strings. Even variable-length strings are limited in length by the number of bits available to a pointer, and by the size of available computer memory. The string length can be stored as a separate integer, which may put an artificial limit on the length, or implicitly through a termination character, usually a character value with all bits zero such as in C programming language.
A string datatype is a datatype modeled on the idea of a formal string. Data types differ according to the programming language or database system, but strings are such an important and useful datatype that they are implemented in nearly every programming language. In some languages, strings are available as primitive types and in others as composite types. The syntax of most high-level programming languages allows for a string, usually quoted in some way, to represent an instance of a string datatype; such a meta-string is called a literal or string literal. For example, some languages like C++ implement strings as templates that can be used with any datatype.
Some languages, such as C++ and Ruby, normally allow the contents of a string to be changed after it has been created. These are called mutable strings. In languages such as Java and Python, the value is fixed and a new string must be created if any alteration should be made. These are called immutable strings.
Security Concerns
The differing memory layout and storage requirements of strings can affect the security of the program accessing the string data. String data is frequently obtained from user input to a program. It is the responsibility of the program to validate the string to ensure that it represents the expected format. Performing limited or no validation of user input can cause a program to be vulnerable to code injection attacks.
.length
Свойство length хранит длину строки, которое обычно совпадает с количеством символов в ней. Если в строке есть непростые символы, вроде эмодзи, они могут удлинять строку больше, чем на единицу.
Длина пустой строки равна 0.
Пример
Скопировать ссылку на секцию «Пример» Скопировано
Как понять
Скопировать ссылку на секцию «Как понять» Скопировано
Строки в JavaScript хранятся в виде последовательности символов в формате UTF-16. UTF-16 использует понятие юнита — одного значения из таблицы UTF-16. Все символы мировых алфавитов представляются в виде одного юнита.
Редкие символы могут использовать несколько юнитов. Если вы решите использовать символы из древнеегипетской письменности, то каждый из них будет занимать два юнита:
Эмодзи состоят из нескольких юнитов. Количество использованных юнитов зависит от эмодзи:
На практике
Скопировать ссылку на секцию «На практике» Скопировано
Николай Лопин советует
Скопировать ссылку на секцию «Николай Лопин советует» Скопировано
Если вы работаете с простым текстом без эмодзи, то свойство length даст вам реальное количество символов в строке.
Не стоит использовать length для измерения количества символов в пользовательском вводе — там могут быть эмодзи.
Простой способ гарантированно посчитать количество символов — воспользоваться спред-синтаксисом. Он превратит строку в массив символов, у которого можно получить длину аналогичным свойством length :
️ С помощью length можно реализовать счётчик символов:
Читайте также
Массив
Ни один язык программирования не обходится без хранения списков значений. JavaScript не исключение.
if . else
В зависимости от условия выполняет один или другой вариант кода.
Почти всё в JavaScript — объект
Что бы мы ни использовали при написании JS кода, почти всё это объекты под капотом.
strlen
Длина строки string в случае успешного выполнения, и 0 , если string пуста.
Примеры
Пример #1 Пример использования strlen()
<?php
$str = ‘abcdef’ ;
echo strlen ( $str ); // 6
$str = ‘ ab cd ‘ ;
echo strlen ( $str ); // 7
?>
Примечания
Замечание:
Функция strlen() возвратит количество байт, а не число символов в строке.
Замечание:
Функция strlen() возвращает null при использовании на массивах, а также выводит ошибку уровня E_WARNING .
Смотрите также
- count() — Подсчитывает количество элементов массива или Countable объекте
- grapheme_strlen() — Получает длину строки в единицах графемы
- iconv_strlen() — Возвращает количество символов в строке
- mb_strlen() — Получает длину строки
User Contributed Notes 9 notes
I want to share something seriously important for newbies or beginners of PHP who plays with strings of UTF8 encoded characters or the languages like: Arabic, Persian, Pashto, Dari, Chinese (simplified), Chinese (traditional), Japanese, Vietnamese, Urdu, Macedonian, Lithuanian, and etc.
As the manual says: «strlen() returns the number of bytes rather than the number of characters in a string.», so if you want to get the number of characters in a string of UTF8 so use mb_strlen() instead of strlen().
<?php
// the Arabic (Hello) string below is: 59 bytes and 32 characters
$utf8 = «السلام علیکم ورحمة الله وبرکاته!» ;
var_export ( strlen ( $utf8 ) ); // 59
echo «<br>» ;
var_export ( mb_strlen ( $utf8 , ‘utf8’ ) ); // 32
?>
The easiest way to determine the character count of a UTF8 string is to pass the text through utf8_decode() first:
<?php
$length = strlen ( utf8_decode ( $s ));
?>
utf8_decode() converts characters that are not in ISO-8859-1 to ‘?’, which, for the purpose of counting, is quite alright.
When checking for length to make sure a value will fit in a database field, be mindful of using the right function.
There are three possible situations:
1. Most likely case: the database column is UTF-8 with a length defined in unicode code points (e.g. mysql varchar(200) for a utf-8 database).
<?php
// ok if php.ini default_charset set to UTF-8 (= default value)
mb_strlen ( $value );
iconv_strlen ( $value );
// always ok
mb_strlen ( $value , «UTF-8» );
iconv_strlen ( $value , «UTF-8» );
// BAD, do not use:
strlen ( utf8_decode ( $value )); // breaks for some multi-byte characters
grapheme_strlen ( $value ); // counts graphemes, not code points
?>
2. The database column has a length defined in bytes (e.g. oracle’s VARCHAR2(200 BYTE))
<?php
// ok, but assumes mbstring.func_overload is 0 in php.ini (= default value)
strlen ( $value );
// ok, forces count in bytes
mb_strlen ( $value , «8bit» )
?>
3. The database column is in another character set (UTF-16, ISO-8859-1, etc. ) with a length defined in characters / code points.
Find the character set used, and pass it explicitly to the length function.
PHP’s strlen function behaves differently than the C strlen function in terms of its handling of null bytes (‘\0’).
In PHP, a null byte in a string does NOT count as the end of the string, and any null bytes are included in the length of the string.
For example, in PHP:
strlen( «te\0st» ) = 5
In C, the same call would return 2.
Thus, PHP’s strlen function can be used to find the number of bytes in a binary string (for example, binary data returned by base64_decode).
We just ran into what we thought was a bug but turned out to be a documented difference in behavior between PHP 5.2 & 5.3. Take the following code example:
$attributes = array( ‘one’ , ‘two’ , ‘three’ );
if ( strlen ( $attributes ) == 0 && ! is_bool ( $attributes )) <
echo «We are in the ‘if’\n» ; // PHP 5.3
> else <
echo «We are in the ‘else’\n» ; // PHP 5.2
>
?>
This is because in 5.2 strlen will automatically cast anything passed to it as a string, and casting an array to a string yields the string «Array». In 5.3, this changed, as noted in the following point in the backward incompatible changes in 5.3 (http://www.php.net/manual/en/migration53.incompatible.php):
«The newer internal parameter parsing API has been applied across all the extensions bundled with PHP 5.3.x. This parameter parsing API causes functions to return NULL when passed incompatible parameters. There are some exceptions to this rule, such as the get_class() function, which will continue to return FALSE on error.»
So, in PHP 5.3, strlen($attributes) returns NULL, while in PHP 5.2, strlen($attributes) returns the integer 5. This likely affects other functions, so if you are getting different behaviors or new bugs suddenly, check if you have upgraded to 5.3 (which we did recently), and then check for some warnings in your logs like this:
strlen() expects parameter 1 to be string, array given in /var/www/sis/lib/functions/advanced_search_lib.php on line 1028
If so, then you are likely experiencing this changed behavior.
I would like to demonstrate that you need more than just this function in order to truly test for an empty string. The reason being that <?php strlen ( null ); ?> will return 0. So how do you know if the value was null, or truly an empty string?
<?php
$foo = null ;
$len = strlen ( null );
$bar = » ;
echo «Length: » . strlen ( $foo ) . «<br>» ;
echo «Length: $len <br>» ;
echo «Length: » . strlen ( null ) . «<br>» ;
if ( strlen ( $foo ) === 0 ) echo ‘Null length is Zero <br>’ ;
if ( $len === 0 ) echo ‘Null length is still Zero <br>’ ;
if ( strlen ( $foo ) == 0 && ! is_null ( $foo )) echo ‘!is_null(): $foo is truly an empty string <br>’ ;
else echo ‘!is_null(): $foo is probably null <br>’ ;
if ( strlen ( $foo ) == 0 && isset( $foo )) echo ‘isset(): $foo is truly an empty string <br>’ ;
else echo ‘isset(): $foo is probably null <br>’ ;
if ( strlen ( $bar ) == 0 && ! is_null ( $bar )) echo ‘!is_null(): $bar is truly an empty string <br>’ ;
else echo ‘!is_null(): $foo is probably null <br>’ ;
if ( strlen ( $bar ) == 0 && isset( $bar )) echo ‘isset(): $bar is truly an empty string <br>’ ;
else echo ‘isset(): $foo is probably null <br>’ ;
?>
// Begin Output:
Length: 0
Length: 0
Length: 0
Null length is Zero
Null length is still Zero
!is_null(): $foo is probably null
isset(): $foo is probably null
!is_null(): $bar is truly an empty string
isset(): $bar is truly an empty string
// End Output
So it would seem you need either is_null() or isset() in addition to strlen() if you care whether or not the original value was null.
There’s a LOT of misinformation here, which I want to correct! Many people have warned against using strlen(), because it is «super slow». Well, that was probably true in old versions of PHP. But as of PHP7 that’s definitely no longer true. It’s now SUPER fast!
I created a 20,00,000 byte string (
20 megabytes), and iterated ONE HUNDRED MILLION TIMES in a loop. Every loop iteration did a new strlen() on that very, very long string.
The result: 100 million strlen() calls on a 20 megabyte string only took a total of 488 milliseconds. And the strlen() calls didn’t get slower/faster even if I made the string smaller or bigger. The strlen() was pretty much a constant-time, super-fast operation
So either PHP7 stores the length of every string as a field that it can simply always look up without having to count characters. Or it caches the result of strlen() until the string contents actually change. Either way, you should now never, EVER worry about strlen() performance again. As of PHP7, it is super fast!
Here is the complete benchmark code if you want to reproduce it on your machine:
$iterations = 100000000 ; // 100 million
$str = str_repeat ( ‘0’ , 20000000 );
// benchmark loop and variable assignment to calculate loop overhead
$start = microtime ( true );
for( $i = 0 ; $i < $iterations ; ++ $i ) <
$len = 0 ;
>
$end = microtime ( true );
$loop_elapsed = 1000 * ( $end — $start );
// benchmark strlen in a loop
$len = 0 ;
$start = microtime ( true );
for( $i = 0 ; $i < $iterations ; ++ $i ) <
$len = strlen ( $str );
>
$end = microtime ( true );
$strlen_elapsed = 1000 * ( $end — $start );
// subtract loop overhead from strlen() speed calculation
$strlen_elapsed -= $loop_elapsed ;
echo «\nstring length: < $len >\ntest took: < $strlen_elapsed >milliseconds\n» ;
How to count characters in a string? (python)
![]()
First of all, don’t use str as a variable name, it will mask the built-in name.
As for counting characters in a string, just use the str.count() method:
If you are just interested in understanding why your current code doesn’t work, you are printing 1 four times because you will find four occurrences of ‘e’, and when an occurrence is found you are printing len(scr) which is always 1 .