Q:

how to find length of character array in c++

// 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
Instead of sizeof() for finding the length of strings or character 
arrays, just use strlen(string_name) with the header file
#include <cstring>   
it's easier.
0
sizeof vs strlen()

Type: Sizeof operator is a unary operator whereas strlen() 
    is a predefined function in C.
Data types supported: Sizeof gives actual size of any type of 
	data (allocated) in bytes (including the null values) whereas 
    get the length of an array of chars/string.
Evaluation size: sizeof() is a compile-time expression giving you 
	the size of a type or a variable’s type. It doesn’t care about 
    the value of the variable. Strlen on the other hand, gives you 
    the length of a C-style NULL-terminated string.
Summary: The two are almost different concepts and used for 
  	different purposes.
0
#include <iostream>

using namespace std;

int main()
{
    char arr[] = "grepper";
    cout << sizeof(arr) << endl;
    return 0;
    //    keep it in mind that character arrays have length of one more than your characters because last one is for \0 to show that word has ended
}
-3

New to Communities?

Join the community