Understand how strlen function works httpwwwcpluspluscomrefe


Understand how strlen function works. http://www.cplusplus.com/reference/cstring/strlen/
Write YOUR OWN strlen function and compare it with strlen function.
Document and comment your solution. Run the program three times to obtain testing results.


Hints: Read the following sample solution only when you need.

#include <iostream>
#include <cstring>
using namespace std;

// Function Prototypes
int mystrlen(char *); // pass by address
int main();

// Function Implementation
int mystrlen(char *cstr)
{
int pos=0;
while (cstr[pos]!=\'\\0\') // looking for \'\\0\' is c-string terminator
pos++;
return pos;
}

int main()
{
const int STRLENGTH=100;
char aline[STRLENGTH]; //static array declaration

cout<<\"Please input a sentence terminated by an enter key. \"<<endl;

cin.getline(aline, STRLENGTH);
// cin>>aline won\'t work for input containing space, tab or enter key.

cout<<aline <<\" contains \"<< mystrlen(aline) << \" number of characters.\"<<endl;
cout<<aline <<\" contains \"<< strlen(aline) << \" number of characters.\"<<endl;

return 0;
}

Solution

#include <iostream>
#include <cstring>

using namespace std;
// Function Prototypes

int mystrlen(char *); // pass by address

int main();
// Function Implementation

int mystrlen(char *s)
{
   // define len to keep the count of the length
   int len = 0;
  
// for loop to travel through each of the letter i sentence to count
for (int i=0; s[i] != 0; i++)
{
       // increase of length
len++;
}
return(len);
}

int main()
{
   const int STRLENGTH=100;
   char aline[STRLENGTH]; //static array declaration
   cout<<\"Please input a sentence terminated by an enter key. \"<<endl;
   cin.getline(aline, STRLENGTH);
   // cin>>aline won\'t work for input containing space, tab or enter key.
   cout<<aline <<\" contains \"<< mystrlen(aline) << \" number of characters.\"<<endl;
   cout<<aline <<\" contains \"<< strlen(aline) << \" number of characters.\"<<endl;
   return 0;
}

 Understand how strlen function works. http://www.cplusplus.com/reference/cstring/strlen/ Write YOUR OWN strlen function and compare it with strlen function. Do
 Understand how strlen function works. http://www.cplusplus.com/reference/cstring/strlen/ Write YOUR OWN strlen function and compare it with strlen function. Do

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site