length of string cpp code example
Example 1: length of string c++
#include <iostream>
#include <string>
int main ()
{
std::string str ("Test string");
std::cout << "The size of str is " << str.length() << " bytes.\n";
return 0;
}
Example 2: length of string in c++
str.length();
Example 3: how to get string length in c++
#include <iostream>
#include <string>
int main()
{
string str = "iftee";
int len = str.length();
cout << "The String Length: " << len << endl;
int len2 = str.size();
cout << "The String Length: " << len2 << endl;
return 0;
}
Example 4: length of a string c++
string str ="hello world";
str.length();
str.size();
Example 5: create a string of length c++
#include <string>
#include <iostream>
int main()
{
std::string s(21, '*');
std::cout << s << std::endl;
return 0;
}
Example 6: how to find the length of an string in c++
#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;
}