how to find length of string in c++
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
Live Demo
#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
Published on 26-Jul-2019 05:51:44
- Related Questions & Answers
- 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
- Find longest length number in a string in C++
- Different Methods to find Prime Number in Python
- Different Methods to find Prime Number in Java
- How to find length of a string without string.h and loop in C?
- Analysis of Different Methods to find Prime Number in Python program
- Find length of a string in python (3 ways)
- Program to find number of different substrings of a string for different queries in Python
- Program to find maximum profit by cutting the rod of different length in C++
- Different Methods to find Prime Number in Python Program
how to find length of string in c++
Source: https://www.tutorialspoint.com/5-different-methods-to-find-length-of-a-string-in-cplusplus
Posted by: destefanothroureept.blogspot.com
0 Response to "how to find length of string in c++"
Post a Comment