CodeBlanks Logo Icon CodeBlanks

String length

Learn the string length with .length() and .size().

length and size

To find how many characters a std::string has you use the length or size method. Both return the same value: std::string w = "Welcome"; std::cout << w.length(); prints 7.

length is preferred when working with text because it reads naturally; size is used for consistency with STL containers. The return type is size_t, an unsigned integer; you should not expect a negative value.

Validating with length

A common use of the length method is validating user input. For example, you can check whether a password has at least 8 characters with if (password.length() >= 8).

Such checks catch wrong or incomplete input early. Because length returns a numeric value, you can use comparison operators (>, <, ==) directly on it.

Practice Print the string length

The word variable is set to "Welcome". Print word.length() with std::cout. The output on a single line must be 7.

Starter code

main.cpp
#include <iostream>
#include <string>

int main() {
    std::string word = "Welcome";
    // Print the length
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <string>

int main() {
    std::string word = "Welcome";
    std::cout << word.length() << std::endl;
    return 0;
}

Expected output

7

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each method to its job

Term Meaning
.length() Character count
.size() Character count (same)
.substr() Takes a part
.append(x) Appends at the end

2 What does std::string w = "Welcome"; w.length() return?

main.cpp
std::string w = "Welcome";
w.length()
  • 7 Correct answer
  • 5
  • 6
  • 8

Explanation: "Welcome" has 7 characters; length() returns 7.

3 Write the length call

Question
std::string w = "Welcome";
int n = w____;
Answer
std::string w = "Welcome";
int n = w.length();

Explanation: .length() returns the character count.

All lessons in Beginner