|
The standard library function
#include <cassert>
#include <iostream>
// strlen: return length of string str
int strlen( char* str )
{
int count;
for ( count = 0; *str != '\0'; ++str )
++count;
return count;
}
int main(int argc, char* argv[])
{
char astr[] = "hello";
int length = strlen( astr );
assert( length == 5 );
return 0;
}
Other possible usages of strlen( "hello, world" ); // a string constant strlen( array ); // an array of characters: char array[100]; strlen( ptr ); // pointer to string: char *ptr; Here is implementation of strlen that employs pointer arithmetic:
// strlen: return length of string str
int strlen( char* str )
{
char* ptr = str;
while ( *ptr != '\0' )
++ptr;
return ptr - str;
}
|
|
Another library function,
#include <cassert>
#include <iostream>
// strcpy: copy src to dst; array subscript version
void strcpy( char* dst, char* src )
{
int idx = 0;
while ( ( dst[ idx ] = src[ idx ] ) != '\0' )
++idx;
}
int main( int argc, char* argv[] )
{
char source[] = "hello";
char destination[ 15 ] = { '\0' };
strcpy( destination, source );
std::cout << destination;
return 0;
}
For contrast, here is a version of strcpy with pointers:
// strcpy: copy src to dst; pointer version
void strcpy( char* dst, char* src )
{
while ( ( *dst = *src ) != '\0' ) {
++dst;
++src;
}
}
In practice, strcpy would not be written as shown above. Experienced C++ programmer would prefer
// strcpy: copy src to dst; pointer version
void strcpy( char* dst, char* src )
{
while ( *dst++ = *src++ )
;
}
|
|
Function
Our first version of strcmp uses array-style access to the individual characters:
#include <cassert>
#include <iostream>
// strcmp: return <0 if one<another, 0 if one==another, >0 if one>another
int strcmp( char* one, char* another )
{
int idx = 0;
for ( ; one[ idx ] == another[ idx ]; ++idx )
if ( one[ idx ] == '\0' )
return 0;
return one[ idx ] - another[ idx ];
}
int main(int argc, char* argv[])
{
char source[] = "hello";
char destination[ 15 ] = { '\0' };
strcpy( destination, source );
assert( strcmp( source, destination ) == 0 );
assert( strcmp( "abc", "xyz" ) < 0 );
assert( strcmp( "D", "AB" ) > 0 );
return 0;
}
The pointer version of strcmp would be as follows:
// strcmp: return <0 if one<another, 0 if one==another, >0 if one>another
int strcmp( char* one, char* another )
{
for ( ; *one == *another; ++one, ++another )
if ( *one == '\0' )
return 0;
return *one - *another;
}
|