Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Understand how strlen function works. http://www.cplusplus.com/reference/cstring

ID: 3777982 • Letter: U

Question


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]!='') // looking for '' 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;
}

Explanation / Answer

#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;
}