Saturday, May 22, 2010

How do i calculate the length of the string without using the strlen function in c++?

Loop on every char of the string until you hit '\0'

How do i calculate the length of the string without using the strlen function in c++?
#include%26lt;iostream.h%26gt;


#include%26lt;conio.h%26gt;


void main()


{


int i;


char j[21];//WILL STORE 20 CHARS,LAST CHAR FOR NULL


clrscr();


cout%26lt;%26lt;"\nENTER STRING";


cin.getline(j,21);


i=0;


while(j[i]!=NULL)


i++;


cout%26lt;%26lt;"\nLENGTH OF STRING IS %d"%26lt;%26lt;i;


getch();


}
Reply:Use a loop counter until you reach the end.
Reply:#include%26lt;iostream.h%26gt;


#include%26lt;conio.h%26gt;


void main()


{


char test[ ]="This is a test string";


int i=0;


while(test[ i ]) // The Loop continues till test[ i ] is NOT Null


{


i++; //increments i , also counts character


}


cout%26lt;%26lt;"Length of test string is "%26lt;%26lt;i-1; // i-1 because i is the number including NULL


getch();


}
Reply:tape measure


No comments:

Post a Comment