Как найти длину строки string

Overview

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

Scope of Article

  • In this article, we will learn to find the length of a String in C.
  • All the methods to find the length of a String will be explained in this article.
  • Every method will be explained using syntax, images, and examples.

Introduction

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

String length in C

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 “” 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 “” and then returning the count.

Let’s take a look at its implementation:
Code

// finding the length of a string using a user-defined function

#include <stdio.h>

// The User-defined method
int str_length(char str[]) {
    // initializing count variable (stores the length of the string)
    int count; 
    
    // incrementing the count till the end of the string
    for (count = 0; str[count] != ''; ++count);
    
    // returning the character count of the string
    return count; 
}

// Driver code
int main() {
    // initializing the array to store string characters
    char str[1000]; 
 
    // inputting the string
    printf("Enter the string: ");
    scanf("%s", str); 
    
    // assigning the count of characters in the string to the length of the string
    int length = str_length(str); 
    
    //  printing the length of string
    printf("The length of the string is %d", length); 
 
    return 0;
}

Output

Enter the string: 567lens
The length of the string is 7

Explanation:

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).

String Length in C using Built-In Library

Syntax


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

Let us take a look at its implementation.
Code


// finding the length of a string using the strlen() function from the string.h library

#include <stdio.h>
#include <string.h>

int main() {
    char str[1000]; // initializing the array to store string characters
 
    // inputting the string
    printf("Enter the string: ");
    scanf("%s", str); 
    
    // initializing the length variable
    int length;
    
    // Using the strlen() function to return the length of the string and assign it to the length variable
    length = strlen(str); 
    
    // printing the length of string
    printf("The length of the string is %d", length); 
 
    return 0;
}

Output :

Enter the string: 5654dds
The length of the string is 7

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).

String Length in C using the sizeof Operator

Syntax


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

Let us take a look at its implementation:
Code

// finding the length of a string using the sizeof operator

#include <stdio.h>

int main() {
    // initializing the string literal
    char str[] = "g4343"; 
    
    // printing the string
    printf("The given string is %sn", str);
    
    // initializing the length variable
    int length;
    
    // using the sizeof operator to find the length of the string
    length = sizeof str; 
    
    // printing the length of string
    printf("The length of the string is %d", length-1); 
 
    return 0;
}

Output

The given string is g4343
The length of the string is 5

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.

Conclusion

  • In C, the length of a string is the count of all its characters except the null character “”.
  • We can find the length of the string using a for loop by counting each character in each iteration.
  • The built-in library function strlen() is used to return the length of a string passed to it.
  • We can also find the length of a C String using the sizeof operator.
string x;
cout << "For the Add Elements Press 'A':n";
{
    char v = getch();
    if (v == 'a') {

        cout << "Enter Elements: n";
        getline(cin, x);  // Как определить длину введенного элемента через strlrn?

        L.ElAdd(x);
    }
    List L;
    L.print();
}

Nicolas Chabanovsky's user avatar

задан 30 мар 2012 в 11:05

navi1893's user avatar

navi1893navi1893

1,84218 золотых знаков75 серебряных знаков131 бронзовый знак

4

x.length()

Класс string на сайте cplusplus.com.

ответ дан 30 мар 2012 в 11:10

andrybak's user avatar

Методы size и length класса string возвращают длину строки:

using namespace std;
string str("Hello world");
basic_string <char>::size_type size, length;

size = str.size();
length = str.length();

ответ дан 30 мар 2012 в 12:23

stanislav's user avatar

stanislavstanislav

34.3k25 золотых знаков95 серебряных знаков213 бронзовых знаков

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    The string is a sequence of characters or an array of characters. The declaration and definition of the string using an array of chars are similar to the declaration and definition of an array of any other data type.

    Important Points

    1. The constructor of the String class will set it to the C++ style string, which ends at the ‘.
    2. The size() function is consistent with other STL containers (like vector, map, etc.) and length() is consistent with most people’s intuitive notion of character strings like a word, sentence, or paragraph. We say a paragraph’s length, not its size, so length() is to make things more readable.

    Methods to find the length of string

    1. Using string::size: The method string::size returns the length of the string, in terms of bytes.
    2. Using string::length: The method string::length returns the length of the string, in terms of bytes.  Both string::size and string::length are synonyms and return the exact same value.
    3. Using the C library function strlen() method: 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.
    4. Using while loop: Using the traditional method, initialize the counter equals 0 and increment the counter from starting of the string to the end of the string (terminating null character).
    5. Using for loop: To initialize the counter equals 0 and increment the counter from starting of the string to the end of the string (terminating null character).

    Examples:

    Input: "Geeksforgeeks"
    Output: 13
    
    Input: "Geeksforgeeks  345"
    Output: 14

    Example:

    C++

    #include <iostream>

    #include <string.h>

    using namespace std;

    int main()

    {

        string str = "GeeksforGeeks";

        cout << str.size() << endl;

        cout << str.length() << endl;

        cout << strlen(str.c_str()) << endl;

        int i = 0;

        while (str[i])

            i++;

        cout << i << endl;

        for (i = 0; str[i]; i++)

            ;

        cout << i << endl;

        return 0;

    }

    Time complexity:
    For all the methods, the time complexity is O(n) as we need to traverse the entire string to find its length.

    Space complexity:
    For all the methods, the space complexity is O(1) as no extra space is required.

    Last Updated :
    10 Mar, 2023

    Like Article

    Save Article

    A sequence of characters or a linear array of character is known as String. Its declaration is same as define other arrays.

    Length of array is the number of characters in the String. There are many in-built method and other methods to find the length of string. Here, we are discussing 5 different methods to find the length of a string in C++.

    1) Using the strlen() method of C − This function returns an integer value of the C. For this you need to pass the string in the form of character array.

    PROGRAM TO ILLUSTRATE THE USE OF strlen() METHOD

    #include <iostream>
    #include <cstring>
    using namespace std;
    int main() {
       char charr[] = "I Love Tutorialspoint";
       int length = strlen(charr);
       cout << "the length of the character array is " << length;
       return 0;
    }

    Output

    the length of the character array is 21

    2) Using the size() method of c++ − It is included in the string library of C++. The return an integer value of the number of characters in the string.

    PROGRAM TO ILLUSTRATE THE USE OF size() METHOD

    #include <iostream>
    #include <string>
    using namespace std;
    int main() {
       string str = "I love tutorialspoint";
       int length = str.size();
       cout << "the length of the string is " << length;
       return 0;
    }

    Output

    The length of the string is 21

    3) Using the for loop − This method does not require any function. It loops through the array and counts the number of elements in it. The loop runs until the ‘/0’ is encountered.

    PROGRAM TO FIND THE LENGTH USING THE FOR LOOP

    #include <iostream>
    #include <string>
    using namespace std;
    int main() {
       string str = "I love tutorialspoint";
       int i;
       for(i=0; str[i]!=''; i++){ }
          cout << "the length of the string is " << i;
       return 0;
    }

    Output

    The length of the string is 21

    4) Using the length() method − In C++ their is a method length() in the string library that returns the number of characters in the string.

    PROGRAM TO FIND THE NUMBER OF CHARACTERS IN STRING USING length() method

    #include <iostream>
    #include <string>
    using namespace std;
    int main() {
       string str = "I love tutorialspoint";
       int length = str.length();
       cout << "the length of the string is " << length;
          return 0;
    }

    Output

    The length of the string is 21

    5) Finding length of string using the while loop − You can count the number of characters in a string using the while loop also. To count the number of characters, you have to use a counter in the while loop and specify the end condition as != ‘’ for the string.

    PROGRAM TO FIND THE LENGTH OF STRING USING WHILE LOOP

    #include <iostream>
    #include <string>
    using namespace std;
    int main() {
       string str = "I love tutorialspoint";
       int length = 0;
       while(str[length] !='' ){
          length++;
       }
       cout<<"The length of the string is "<< length;
       return 0;
    }

    Output

    The length of the string is 21

    Добавлено 2 октября 2021 в 16:01

    После того, как вы создали строку, часто бывает полезно узнать ее длину. Здесь в игру вступают операции с длиной и емкостью.

    Длина строки

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

    size_type string::length() const
    size_type string::size() const

    Обе эти функции возвращают текущее количество символов в строке, исключая завершающий ноль.

    Пример кода:

    string sSource("012345678");
    cout << sSource.length() << endl;

    Вывод:

    9

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

    bool string::empty() const

    Возвращает true, если в строке нет символов, иначе – false.

    Пример кода:

    string sString1("Not Empty");
    cout << (sString1.empty() ? "true" : "false") << endl;
    string sString2; // пустая
    cout << (sString2.empty() ? "true" : "false")  << endl;

    Вывод:

    false
    true

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

    size_type string::max_size() const

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

    Пример кода:

    string sString("MyString");
    cout << sString.max_size() << endl;

    Вывод:

    4294967294

    Емкость строки

    Емкость (вместимость) строки показывает, сколько памяти выделено объектом строки для хранения ее содержимого. Это значение измеряется в строковых символах, исключая символ завершающего нуля. Например, строка с емкостью 8 может содержать 8 символов.

    size_type string::capacity() const

    Возвращает количество символов, которое строка может хранить без перераспределения памяти.

    Пример кода:

    string sString("01234567");
    cout << "Length: " << sString.length() << endl;
    cout << "Capacity: " << sString.capacity() << endl;

    Вывод:

    Length: 8
    Capacity: 15

    Обратите внимание, что емкость больше, чем длина строки! Хотя длина нашей строки равна 8, на самом деле она занимала достаточно памяти для 15 символов! Зачем так сделано?

    Здесь важно понимать, что если пользователь хочет поместить в строку больше символов, чем позволяет ее емкость, то для получения большей емкости строка должна быть перераспределена в памяти. Например, если строка имеет длину и емкость 8, то добавление любых символов в строку приведет к переразмещению объекта в памяти. Сделав емкость больше размера фактической строки, пользователь получил некоторое буферное пространство для расширения строки до необходимости перераспределения.

    Как оказалось, перераспределение – это плохо по нескольким причинам:

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

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

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

    string sString("0123456789abcde");
    cout << "Length: " << sString.length() << endl;
    cout << "Capacity: " << sString.capacity() << endl;

    Эта программа выводит:

    Length: 15
    Capacity: 15

    Результаты могут отличаться в зависимости от компилятора.

    Давайте добавим к строке один символ и посмотрим, как изменится емкость:

    string sString("0123456789abcde");
    cout << "Length: " << sString.length() << endl;
    cout << "Capacity: " << sString.capacity() << endl;
    
    // Теперь добавим новый символ
    sString += "f";
    cout << "Length: " << sString.length() << endl;
    cout << "Capacity: " << sString.capacity() << endl;

    Это дает следующий результат:

    Length: 15
    Capacity: 15
    Length: 16
    Capacity: 31

    void string::reserve()
    void string::reserve(size_type unSize)

    Второй вариант этой функции устанавливает емкость строки минимум на unSize (она может быть больше). Обратите внимание, что для этого может потребоваться перераспределение.

    Если вызывается первый вариант этой функции или второй вариант вызывается с unSize, меньшим, чем текущая емкость, функция попытается уменьшить емкость, чтобы она соответствовала длине. Этот запрос необязателен для выполнения.

    Пример кода:

    string sString("01234567");
    cout << "Length: " << sString.length() << endl;
    cout << "Capacity: " << sString.capacity() << endl;
    
    sString.reserve(200);
    cout << "Length: " << sString.length() << endl;
    cout << "Capacity: " << sString.capacity() << endl;
    
    sString.reserve();
    cout << "Length: " << sString.length() << endl;
    cout << "Capacity: " << sString.capacity() << endl;

    Вывод:

    Length: 8
    Capacity: 15
    Length: 8
    Capacity: 207
    Length: 8
    Capacity: 207

    В этом примере показаны две интересные вещи. Во-первых, хотя мы запросили емкость 200, на самом деле мы получили емкость 207. Гарантируется, что емкость всегда будет не меньше, чем вы запросили, но может быть и больше. Затем мы запросили изменение емкости, чтобы она соответствовала длине строки. Этот запрос был проигнорирован, так как емкость не изменилась.

    Если вы заранее знаете, что собираетесь создать большую строку, выполняя множество строковых операций, которые увеличивают размер строки, вы можете избежать многократного перераспределения строки в памяти, сразу установив для строки необходимую ей емкость:

    #include <iostream>
    #include <string>
    #include <cstdlib> // для rand() и srand()
    #include <ctime>   // для time()
    
    using namespace std;
    
    int main()
    {
        std::srand(std::time(nullptr)); // инициализация генератора случайных чисел
    
        string sString{};    // длина 0
        sString.reserve(64); // резервируем 64 символа
    
        // Заполняем строку случайными строчными буквами
        for (int nCount{ 0 }; nCount < 64; ++nCount)
            sString += 'a' + std::rand() % 26;
    
        cout << sString;
    }

    Результат этой программы будет меняться каждый раз. Вот результат одного выполнения:

    wzpzujwuaokbakgijqdawvzjqlgcipiiuuxhyfkdppxpyycvytvyxwqsbtielxpy

    Вместо того чтобы перераспределять sString несколько раз, мы устанавливаем емкость один раз, а затем заполняем строку. Это может очень влиять на производительность при формировании больших строк с помощью конкатенации.

    Теги

    C++ / CppLearnCppstd::stringstd::wstringSTL / Standard Template Library / Стандартная библиотека шаблоновДля начинающихЕмкостьОбучениеПрограммирование

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