S length 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
Input
Output
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,
Input
Output
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:
- 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.
- We can also scanset characters inside the scanf() function
1. Example of String Input using gets()
Input
Output
2. Example of String Input using scanset
Input
Output
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:
Output:
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, то добавление новых символов в строку приведет к её перераспределению. Делая ёмкость строки больше её длины, мы предоставляем пользователю некоторое буферное пространство для расширения строки (добавление новых символов).
Но в перераспределении есть также несколько нюансов:
Во-первых, это сравнительно ресурсозатратно. Сначала должна быть выделена новая память. Затем каждый символ строки копируется в новую память. Если строка большая, то тратится много времени. Наконец, старая память должна быть удалена/освобождена. Если вы делаете много перераспределений, то этот процесс может значительно снизить производительность вашей программы.
Во-вторых, всякий раз, когда строка перераспределяется, её содержимое получает новый адрес памяти. Это означает, что все текущие ссылки, указатели и итераторы строки становятся недействительными!
Обратите внимание, не всегда строки создаются с ёмкостью, превышающей её длину. Рассмотрим следующую программу:
How to get the number of characters in a std::string?
How should I get the number of characters in a string in C++?
12 Answers 12
If you’re using a std::string , call length() :
If you’re using a c-string, call strlen() .
Or, if you happen to like using Pascal-style strings (or f***** strings as Joel Spolsky likes to call them when they have a trailing NULL), just dereference the first character.
When dealing with C++ strings (std::string), you’re looking for length() or size(). Both should provide you with the same value. However when dealing with C-Style strings, you would use strlen().
Output:
For Unicode
Several answers here have addressed that .length() gives the wrong results with multibyte characters, but there are 11 answers and none of them have provided a solution.
The case of Z͉̳̺ͥͬ̾a̴͕̲̒̒͌̋ͪl̨͎̰̘͉̟ͤ̀̈̚͜g͕͔̤͖̟̒͝ͅo̵̡̡̼͚̐ͯ̅ͪ̆ͣ̚
First of all, it’s important to know what you mean by «length». For a motivating example, consider the string «Z͉̳̺ͥͬ̾a̴͕̲̒̒͌̋ͪl̨͎̰̘͉̟ͤ̀̈̚͜g͕͔̤͖̟̒͝ͅo̵̡̡̼͚̐ͯ̅ͪ̆ͣ̚» (note that some languages, notably Thai, actually use combining diacritical marks, so this isn’t just useful for 15-year-old memes, but obviously that’s the most important use case). Assume it is encoded in UTF-8. There are 3 ways we can talk about the length of this string:
95 bytes
50 codepoints
5 graphemes
Finding the lengths using ICU
There are C++ classes for ICU, but they require converting to UTF-16. You can use the C types and macros directly to get some UTF-8 support:
Boost.Locale wraps ICU, and might provide a nicer interface. However, it still requires conversion to/from UTF-16.
It depends on what string type you’re talking about. There are many types of strings:
- const char* — a C-style multibyte string
- const wchar_t* — a C-style wide string
- std::string — a «standard» multibyte string
- std::wstring — a «standard» wide string
For 3 and 4, you can use .size() or .length() methods.
For 1, you can use strlen() , but you must ensure that the string variable is not NULL (=== 0)
For 2, you can use wcslen() , but you must ensure that the string variable is not NULL (=== 0)
There are other string types in non-standard C++ libraries, such as MFC’s CString , ATL’s CComBSTR , ACE’s ACE_CString , and so on, with methods such as .GetLength() , and so on. I can’t remember the specifics of them all right off the top of my head.
The STLSoft libraries have abstracted this all out with what they call string access shims, which can be used to get the string length (and other aspects) from any type. So for all of the above (including the non-standard library ones) using the same function stlsoft::c_str_len() . This article describes how it all works, as it’s not all entirely obvious or easy.
C library function — strlen()
The C library function size_t strlen(const char *str) computes the length of the string str up to, but not including the terminating null character.
Declaration
Following is the declaration for strlen() function.
Parameters
str − This is the string whose length is to be found.
Return Value
This function returns the length of string.
Example
The following example shows the usage of strlen() function.
Let us compile and run the above program that will produce the following result −