Length c что это
Перейти к содержимому

Length c что это

  • автор:

String Length in C

In C, a string is an array of characters that is terminated with a null character "\0" . The length of a string will be determined by counting all the characters in the string (except for the null character) .


The string length in C is equal to the count of all the characters in it (except the null character "\0").

For Example, the string "gfddf" has a length of 5 and the string "4343" has a length of 4 .

Note: In C, a String is an array of characters that is terminated with a null character "\0" to indicate the end of the string.

How to Find the String Length in C?

We can find the length of a String by counting all the characters in it (before the null character) using a for loop. We can also use the built-in string.h library function strlen() or the sizeof() operator.
Let us understand how to use these methods in the coming sections.

String Length in C using a User-Defined Function

We can find the length of a string using a user-defined function by iterating over the string in a for loop and incrementing the count of characters (length) by 1 till it reaches the null character "\0" and then returning the count.

Let's take a look at its implementation:



In the above example, we are finding the length of a string by iterating over it in a for loop and incrementing the count by 1 in each iteration till it reaches the null character. The value of count after the end of the for loop will be equal to the length of the string.

String Length in C Using Built-In Library Function

The length of a string can be found using the built-in library function strlen() in string.h header file. It returns the length of the string passed to it (ignoring the null character).


The string is passed to the strlen() function, which returns its length.

Let us take a look at its implementation.

Output :

In the above example, we are finding the length of a string by using the string.h library function strlen() , which returns the length of the string passed to it.

String Length in C Using the sizeof() Operator

We can also find the length of a string using the sizeof() Operator in C . The sizeof is a unary operator which returns the size of an entity (variable or value).

The value is written with the sizeof operator which returns its size (in bytes).

Let us take a look at its implementation:


In the above example, we are finding the length of the string "g4343" using the sizeof operator in C. The sizeof operator returns its length as 6 in the output as It returns the size of an operand, not the string length (including null values). But here, if we print length-1 then we get the length of the string.

std:: string::length

This is the number of actual bytes that conform the contents of the string, which is not necessarily equal to its storage capacity.

Note that string objects handle bytes without knowledge of the encoding that may eventually be used to encode the characters it contains. Therefore, the value returned may not correspond to the actual number of encoded characters in sequences of multi-byte or variable-length characters (such as UTF-8).

Both string::size and string::length are synonyms and return the exact same value.


Return Value

The number of bytes in the string.

size_t is an unsigned integral type (the same as member type string::size_type ).

Strings in C

A String in C programming is a sequence of characters terminated with a null character ‘\0’. The C String is stored as an array of characters. The difference between a character array and a C string is the string is terminated with a unique character ‘\0’.

C String Declaration Syntax

Declaring a string in C is as simple as declaring a one-dimensional array. Below is the basic syntax for declaring a string.

In the above syntax str_name is any name given to the string variable and size is used to define the length of the string, i.e the number of characters strings will store.

There is an extra terminating character which is the Null character (‘\0’) used to indicate the termination of a string that differs strings from normal character arrays.

C String Initialization

A string in C can be initialized in different ways. We will explain this with the help of an example. Below are the examples to declare a string with the name str and initialize it with “GeeksforGeeks”.

Ways to Initialize a String in C

We can initialize a C string in 4 different ways which are as follows:

1. Assigning a string literal without size

String literals can be assigned without size. Here, the name of the string str acts as a pointer because it is an array.

2. Assigning a string literal with a predefined size

String literals can be assigned with a predefined size. But we should always account for one extra space which will be assigned to the null character. If we want to store a string of size n then we should always declare a string with a size equal to or greater than n+1.

3. Assigning character by character with size

We can also assign a string character by character. But we should remember to set the end character as ‘\0’ which is a null character.

4. Assigning character by character without size

We can assign character by character without size with the NULL character at the end. The size of the string is determined by the compiler automatically.

Note: When a Sequence of characters enclosed in the double quotation marks is encountered by the compiler, a null character ‘\0’ is appended at the end of the string by default.

Below is the memory representation of the string “Geeks”.

Note: After declaration, if we want to assign some other text to the string, we have to assign it one by one or use built-in strcpy() function because the direct assignment of string literal to character arrray is only possible in declration.

Let us now look at a sample program to get a clear understanding of declaring, and initializing a string in C, and also how to print a string with its size.

C String Example

We can see in the above program that strings can be printed using normal printf statements just like we print any other variable. Unlike arrays, we do not need to print a string, character by character.

Note: The C language does not provide an inbuilt data type for strings but it has an access specifier “%s” which can be used to print and read strings directly.

Read a String Input From the User

The following example demonstrates how to take string input using scanf() function in C



You can see in the above program that the string can also be read using a single scanf statement. Also, you might be thinking that why we have not used the ‘&’ sign with the string name ‘str’ in scanf statement! To understand this you will have to recall your knowledge of scanf.
We know that the ‘&’ sign is used to provide the address of the variable to the scanf() function to store the value read in memory. As str[] is a character array so using str without braces ‘[‘ and ‘]’ will give the base address of this string. That’s why we have not used ‘&’ in this case as we are already providing the base address of the string to scanf.

Now consider one more example,



Here, the string is read-only till the whitespace is encountered. To read the string containing whitespace characters we can use the methods described below:

How to Read a String Separated by Whitespaces in C?

We can use multiple methods to read a string separated by spaces in C. The two of the common ones are:

  1. We can use the fgets() function to read a line of string and gets() to read characters from the standard input (stdin) and store them as a C string until a newline character or the End-of-file (EOF) is reached.
  2. We can also scanset characters inside the scanf() function

1. Example of String Input using gets()



2. Example of String Input using scanset



C String Length

The length of the string is the number of characters present in the string except for the NULL character. We can easily find the length of the string using the loop to count the characters from the start till the NULL character is found.

Passing Strings to Function

As strings are character arrays, we can pass strings to functions in the same way we pass an array to a function. Below is a sample program to do this:


Note: We can’t read a string value with spaces, we can use either gets() or fgets() in the C programming language.

Strings and Pointers in C

In Arrays, the variable name points to the address of the first element. Similar to arrays, In C, we can create a character pointer to a string that points to the starting address of the string which is the first character of the string. The string can be accessed with the help of pointers as shown in the below example.

Урок №202. Длина и ёмкость std::string

При создании строки не помешало бы указать её длину и ёмкость (или хотя бы знать эти параметры).

Длина std::string

Длина строки — это количество символов, которые она содержит. Есть две идентичные функции для определения длины строки:

size_type string::length() const

size_type string::size() const

Обе эти функции возвращают текущее количество символов, которые содержит строка, исключая нуль-терминатор. Например:

Хотя также можно использовать функцию length() для определения того, содержит ли строка какие-либо символы или нет, эффективнее использовать функцию empty():

bool string::empty() const — эта функция возвращает true , если в строке нет символов, и false — в противном случае.

Есть еще одна функция, связанная с длиной строки, которую вы, вероятно, никогда не будете использовать, но мы все равно её рассмотрим:

size_type string::max_size() const — эта функция возвращает максимальное количество символов, которое может хранить строка. Это значение может варьироваться в зависимости от операционной системы и архитектуры операционной системы.

Ёмкость std::string

Ёмкость строки — это максимальный объем памяти, выделенный строке для хранения содержимого. Это значение измеряется в символах строки, исключая нуль-терминатор. Например, строка с ёмкостью 8 может содержать 8 символов.

size_type string::capacity() const — эта функция возвращает количество символов, которое может хранить строка без дополнительного перераспределения/перевыделения памяти.

Length: 10
Capacity: 15

Примечание: Запускать эту и следующие программы следует в полноценных IDE, а не в веб-компиляторах.

Обратите внимание, ёмкость строки больше её длины! Хотя длина нашей строки равна 10, памяти для неё выделено аж на 15 символов! Почему так?

Здесь важно понимать, что, если пользователь захочет поместить в строку больше символов, чем она может вместить, строка будет перераспределена и, соответственно, ёмкость будет больше. Например, если строка имеет длину и ёмкость равную 10, то добавление новых символов в строку приведет к её перераспределению. Делая ёмкость строки больше её длины, мы предоставляем пользователю некоторое буферное пространство для расширения строки (добавление новых символов).

Но в перераспределении есть также несколько нюансов:

Во-первых, это сравнительно ресурсозатратно. Сначала должна быть выделена новая память. Затем каждый символ строки копируется в новую память. Если строка большая, то тратится много времени. Наконец, старая память должна быть удалена/освобождена. Если вы делаете много перераспределений, то этот процесс может значительно снизить производительность вашей программы.

Во-вторых, всякий раз, когда строка перераспределяется, её содержимое получает новый адрес памяти. Это означает, что все текущие ссылки, указатели и итераторы строки становятся недействительными!

Обратите внимание, не всегда строки создаются с ёмкостью, превышающей её длину. Рассмотрим следующую программу:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *