• Register
2 votes
27 views

Problem:

How can I find the length of a string in c++?

15.3k points
reopened by

Please log in or register to answer this question.

1 Answer

1 vote
 
Best answer

Solution:

There are several ways to find the length of a string in c++

  1. Using string::size

  2. Using string::length

  3. Using C library function strlen() method

  4. Using while loop

  5. Using for loop

I am trying to put all methods in my single program for your better understanding.

#include <iostream> 
#include <string.h> 
using namespace std; 
int main() 
{ 
    // String obj 
    string str = "Hello World!"; 
  
    // 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; 
} 

Every time you’ll get the output: 12

Thanks

 

94.3k points
selected by