Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
std::string::find_last_not_of in C++
Next article icon

5 Different Methods to Find Length of a String in C++

Last Updated : 19 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Examples:

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

Important Points

  1. The constructor of the String class will set it to the C++ style string, which ends at the ‘\0‘.
  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 a String

There are few methods to find the length of a string is mentioned below:

  • Using string::size
  • Using string::length: 
  • Using the C library function strlen() method: 
  • Using while loop: 
  • Using for loop: 

1. Using string::size

The method string::size returns the length of the string, in terms of bytes.

Below is the implementation of the above method:

C++




// C++ program to find length
// of a string
#include <iostream>
#include <string.h>
using namespace std;
 
// Driver code
int main()
{
    // String obj
    string str = "GeeksforGeeks";
 
    // size of string object using size() method
    cout << str.size() << endl;
 
    return 0;
}
 
 
Output
13

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.

Below is the implementation of the above method:

C++




// C++ program to find length
// of a string
#include <iostream>
#include <string.h>
using namespace std;
 
// Driver code
int main()
{
    // String obj
    string str = "GeeksforGeeks";
 
    // size of string object using length method
    cout << str.length() << endl;
 
    return 0;
}
 
 
Output
13

3. Using 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.

Below is the implementation of the above method:

C++




// C++ program to find length
// of a string
#include <iostream>
#include <string.h>
using namespace std;
 
// Driver code
int main()
{
    // String obj
    string str = "GeeksforGeeks";
 
    // size using old style
    // size of string object using strlen function
    cout << strlen(str.c_str()) << endl;
 
    return 0;
}
 
 
Output
13

4. Using a 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).

Below is the implementation of the above method:

C++




// C++ program to find length
// of a string
#include <iostream>
#include <string.h>
using namespace std;
 
// Driver code
int main()
{
    // String obj
    string str = "GeeksforGeeks";
 
    // The constructor of string will set it to the
    // C-style string,
    // which ends at the '\0'
 
    // size of string object Using while loop
    // while 'NOT NULL'
    int i = 0;
    while (str[i])
        i++;
    cout << i << endl;
 
    return 0;
}
 
 
Output
13

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

Below is the implementation of the above method:

C++




// C++ program to find length
// of a string
#include <iostream>
#include <string.h>
using namespace std;
 
// Driver code
int main()
{
    int i;
   
    // String obj
    string str = "GeeksforGeeks";
 
    // The constructor of string will set it to the
    // C-style string,
    // which ends at the '\0'
 
    // size of string object using for loop
    // for(; NOT NULL
    for (i = 0; str[i]; i++);
    cout << i << endl;
   
    return 0;
}
 
 
Output
13

The complexity of the method above:

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.



Next Article
std::string::find_last_not_of in C++
author
kartik
Improve
Article Tags :
  • C++
  • Strings
  • cpp-string
Practice Tags :
  • CPP
  • Strings

Similar Reads

  • Find last index of a character in a string
    Given a string str and a character x, find last index of x in str. Examples : Input : str = "geeks", x = 'e' Output : 2 Last index of 'e' in "geeks" is: 2 Input : str = "Hello world!", x = 'o' Output : 7 Last index of 'o' is: 7 Recommended PracticeLast index of a character in the stringTry It! Metho
    8 min read
  • Different ways to access characters in a given String in C++
    String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character. There are several ways to access substrings and individual characters of a string. The string class supports the following functions for this purpose: operator[]at()subst
    4 min read
  • Length Of Last Word in a String
    Given a string s consisting of upper/lower-case alphabets and empty space characters ' ', return the length of the last word in the string. If the last word does not exist, return 0. Examples: Input : str = "Geeks For Geeks"Output : 5length(Geeks)= 5Input : str = "Start Coding Here"Output : 4length(
    14 min read
  • Converting Number to String in C++
    In C++, converting integers to strings or converting numbers to strings or vice-versa is actually a big paradigm shift in itself. In general or more specifically in competitive programming there are many instances where we need to convert a number to a string or string to a number. Let's look at som
    4 min read
  • std::string::find_last_not_of in C++
    It searches the string for the first character, from the end of the string, that does not match any of the characters specified in its arguments. Return value : Index of first unmatched character when successful or string::npos if no such character found. Syntax 1: Search for the last character that
    6 min read
  • Difference between strlen() and sizeof() for string in C
    sizeof() Sizeof operator is a compile time unary operator which can be used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t.sizeof can be applied to any data-type, including primitive types such as integer and floating-point ty
    2 min read
  • Extract all integers from string in C++
    Given a string, extract all integers words from it. Examples : Input : str = "geeksforgeeks 12 13 practice" Output : 12 13 Input : str = "1: Prakhar Agrawal, 2: Manish Kumar Rai, 3: Rishabh Gupta" Output : 1 2 3 Input : str = "Ankit sleeps at 4 am." Output : 4 The idea is to use stringstream:, objec
    2 min read
  • Convert String to int in C++
    Converting a string to int is one of the most frequently encountered tasks in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we c
    7 min read
  • Find one extra character in a string
    Given two strings which are of lengths n and n+1. The second string contains all the characters of the first string, but there is one extra character. Your task is to find the extra character in the second string. Examples: Input : string strA = "abcd"; string strB = "cbdae"; Output : e string B con
    15+ min read
  • Count occurrences of a word in string
    Given a two strings s and word. The task is to count the number of occurrences of the string word in the string s.Note: The string word should appear in s as a separate word, not as a substring within other words. Examples: Input: s = "GeeksforGeeks A computer science portal for geeks", word = "port
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences