- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
5 Different methods to find length of a string in C++?
Here we will see five different ways to get the string lengths in C++. In C++ we can use the traditional character array string, and C++ also has String class. In different area there are different methods of calculating the string lengths.
The C++ String class has length() and size() function. These can be used to get the length of a string type object. To get the length of the traditional C like strings, we can use the strlen() function. That is present under the cstring header file. Another two approaches are straight forward. One by using the while loop, and another is by using the for loop.
Let us see the examples to get the idea.
Example
#include<iostream> #include<cstring> using namespace std; main() { string myStr = "This is a sample string"; char myStrChar[] = "This is a sample string"; cout << "String length using string::length() function: " << myStr.length() <<endl; cout << "String length using string::size() function: " << myStr.size() <<endl; cout << "String length using strlen() function for c like string: " << strlen(myStrChar) <<endl; cout << "String length using while loop: "; char *ch = myStrChar; int count = 0; while(*ch != '\0'){ count++; ch++; } cout << count << endl; cout << "String length using for loop: "; count = 0; for(int i = 0; myStrChar[i] != '\0'; i++){ count++; } cout << count; }
Output
String length using string::length() function: 23 String length using string::size() function: 23 String length using strlen() function for c like string: 23 String length using while loop: 23 String length using for loop: 23
- Related Articles
- 5 Different methods to find the length of a string in C++?
- Different methods to reverse a string in C/C++
- Different Methods to find Prime Numbers in C#
- C++ Program to Find the Length of a String
- C program to find the length of a string?
- Analysis of Different Methods to find Prime Number in Python
- Different Methods to find Prime Number in Python
- Different Methods to find Prime Number in Java
- Find longest length number in a string in C++
- How to find length of a string without string.h and loop in C?
- Different methods to append a single character to a string or char array in Java
- Analysis of Different Methods to find Prime Number in Python program
- Different Methods to find Prime Number in Python Program
- Program to find number of different substrings of a string for different queries in Python
- C# String Methods

Advertisements