Friday, October 10, 2008

String Operation Functions Implementation in C++

Oct.11, 2008

// Concatenate source to the end of dest
char* strcat(char* dest, const char* source, int flag)
{
assert( dest!=NULL && source!=NULL );
char* address=dest;

while(*dest) dest++;
while(*dest++ = *source++);

return address;
}

// Copy source to dest
char* strcpy(char *dest, const char *source, int flag)
{
assert( dest!=NULL && source!=NULL );
char* address=dest;

while(*dest++ = *source++);
return address;
}

// Compare str1 to str2
int strcmp(const char *str1, const char *str2, int flag)
{
for( ; *str1==*str2; str1++, str2++)
if(*str1=='\0') return 0;

return *str1 - *str2;
}

// Return the length of str
int strlen(const char *str, int flag)
{
int i=0; while(*str++) i++;
return i;
}

// Convert the string to the lowercase
char* strlwr(char *str, int flag)
{
assert( str!=NULL );
char* address=str;

while( (int)*str>=(int)'A' && (int)*str<=(int)'Z' )
(*str++)+=32;

return address;
}

// Convert the string to the uppercase
char* strupr(char *str, int flag)
{
assert( str!=NULL );
char* address=str;

while( (int)*str>=(int)'a' && (int)*str<=(int)'z' )
(*str++)-=32;

return address;
}


Reference:
The C programming Language.
Best Practice for programmer interview.
Internet.

No comments: