(Write Your Own String Length Function) Write two versions of function strlen in Fig. 22.21. The first version should use array subscripting, and the second should use pointers and pointer arithmetic.

What will be an ideal response?

```
#include
using namespace std;

// prototype
unsigned long stringLength1( const char * );
unsigned long stringLength2( const char * );

int main()
{
char string[ 100 ];

cout << "Enter a string: ";
cin >> string;

cout << "\nAccording to stringLength1 the string length is: "
<< stringLength1( string )
<< "\nAccording to stringLength2 the string length is: "
<< stringLength2( string ) << endl;

return 0; // indicate successful termination
} // end main

// finding string length using arrays
unsigned long stringLength1( const char *sPtr )
{
int length;

// array subscript notation
for ( length = 0; sPtr[ length ] != '\0'; length++ )
; // empty body

return length;
} // end function stringLength1

// finding string length using pointers
unsigned long stringLength2( const char *sPtr )
{
int length;

// pointer notation
for ( length = 0; *sPtr != '\0'; sPtr++, length++ )
; // empty body

return length;
} // end function stringLength2
```
Enter a string: length
According to stringLength1 the string length is: 6
According to stringLength2 the string length is: 6

Computer Science & Information Technology

You might also like to view...

Given a list of candy bars in a field called Item and their prices in a field called Price on an empty PivotTable, how would you find out how many of each type of candy bar you have?

A) Drag Item to the ROWS areas. B) Drag Item to both the VALUES and the ROWS area. C) Drag Item to the COLUMNS area. D) Drag Price to the ROWS and Item to the VALUES area.

Computer Science & Information Technology

A ________ chart is generally used for showing the relationship of the parts to the whole

A) pie B) Scatter C) stacked column D) line

Computer Science & Information Technology