Here we will see various ways to find length of string in C++. We can do this in two ways, one is by using inbuilt functions such as length(), and size(), and another way is to find using a loop manually.
Method 1: Using length() or size()
#include <iostream>
using namespace std;
int main() {
string str = "The Crazy Programmer";
cout << "Length of the string is: " << str.length() << endl;
cout << "Length of the string is: " << str.size();
return 0;
}
Output:
Length of the string is: 20
Length of the string is: 20
Method 2: Using Loop
We can use any loop to iterate through the string to find its length.
#include <iostream>
using namespace std;
int main() {
string str = "Hello World";
int i;
for(i = 0; str[i]; i++);
cout << "Length of the string is: " << i;
return 0;
}
Output:
Length of the string is: 11
hey, i get a error that “gets should have a prototype”.
I too have the same problem.
can we use strlen instead of for loop???
I guess you did not read the title of the blog. It clearly says “Without using Library functions”. The function “strlen()” is library function.
Do we need to use string header file in this program
Yes you must……
Thank you guys plz make some more programs it helos us so much