C++ String Length

To get the length of a string, you use the .length() or .size() member functions.

Example:


#include <iostream>
#include <string>
using namespace std;

int main() {

    string str = "Hello Friends!";
    // length of the string
    cout << str.length() << "\n";
    
    return 0;
}

Output:

14

Use size() to get the length of the string.


#include <iostream>
#include <string>
using namespace std;

int main() {

    string str = "Hello Friends!";
    // length of the string
    cout << str.size() << "\n";
    
    return 0;
}

Output:

14

C++ String Length – Interview Questions

Q 1: How to find string length?
Ans: Using length() or size().
Q 2: Do length() and size() differ?
Ans: No.
Q 3: Does length include null character?
Ans: No.
Q 4: Return type of length()?
Ans: size_t.
Q 5: Can length be zero?
Ans: Yes.

C++ String Length – Objective Questions (MCQs)

Q1. Which function is used to find the length of a string in C++?






Q2. What will be the output of this code?

string s = "C++";
cout << s.length();






Q3. What will happen if you call length() on an empty string?






Q4. Which function can be used as an alternative to length()?






Q5. What data type does length() function return?






Related C++  String Length Topics