C++ Program to Find String Length

Write a C++ Program to Find String Length with an example. In C++, there is a length function to find the string length.

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string txt;
	
	cout << "\nPlease Enter the String to find Length  =  ";
	getline(cin, txt);
	
	int len = txt.length();
	cout<< "\nThe Length of '" << txt << "' String = " << len;
		
 	return 0;
}
C++ Program to Find String Length 1

In C++, there is a size function that returns the length of a string.

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string txt;
	
	cout << "\nPlease Enter the String to find Length  =  ";
	getline(cin, txt);
	
	int len = txt.size();
	cout<< "\nThe Length of '" << txt << "' String = " << len;
		
 	return 0;
}
Please Enter the String to find Length  =  hello world

The Length of 'hello world' String = 11

C++ Program to Find String Length using a While loop

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string txt;
	
	cout << "\nPlease Enter the String to find Length  =  ";
	getline(cin, txt);
	
	int i = 0;
	while(txt[i])
	{
		i++;
	}
	cout<< "\nThe Length of '" << txt << "' String = " << i;
		
 	return 0;
}
Please Enter the String to find Length  =  c++ programming

The Length of 'c++ programming' String = 15

C++ Program to Find String Length using For loop

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string txt;
	int i;
	
	cout << "\nPlease Enter the String to find Length  =  ";
	getline(cin, txt);
	
	for (i = 0; txt[i]; i++);

	cout<< "\nThe Length of '" << txt << "' String = " << i;
		
 	return 0;
}
Please Enter the String to find Length  =  hello world!

The Length of 'hello world!' String = 12