yewido
24
Q:

length of string c++

// string::length
#include <iostream>
#include <string>

int main ()
{
  std::string str ("Test string");
  std::cout << "The size of str is " << str.length() << " bytes.\n";
  return 0;
}
15
#include <iostream>
#include <string>

int main()
{
  string str = "iftee";
  
  //method 1: using length() function
  int len = str.length();
  cout << "The String Length: " << len << endl;
  
  //method 2: using size() function
  int len2 = str.size();
  cout << "The String Length: " << len2 << endl;
  
  return 0;
}
1
string str ="hello world"; 
//different ways to find length of a string: 
str.length(); 
str.size(); 
2
str.length();
1

  string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt 
  string is: " << txt.length(); 
5

  string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt 
  string is: " << txt.size(); 
4
// CPP program to illustrate 
// Different methods to find length 
// of a string 
#include <iostream> 
#include <string.h> 
using namespace std; 
int main() 
{ 
    // String obj 
    string str = "GeeksforGeeks"; 
  
    // 1. size of string object using size() method 
    cout << str.size() << endl; 
  
    // 2. size of string object using length method 
    cout << str.length() << endl; 
  
    // 3. size using old style 
    // size of string object using strlen function 
    cout << strlen(str.c_str()) << endl; 
  
    // The constructor of string will set it to the 
    // C-style string, 
    // which ends at the '\0' 
  
    // 4. size of string object Using while loop 
    // while 'NOT NULL' 
    int i = 0; 
    while (str[i]) 
        i++; 
    cout << i << endl; 
  
    // 5. size of string object using for loop 
    // for(; NOT NULL  
    for (i = 0; str[i]; i++) 
        ; 
    cout << i << endl; 
  
    return 0; 
} 
2
#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;
}
0

New to Communities?

Join the community