Monday 10 September 2012

C++ ( Tutorial III )

Classes And Functions 

Some compilers may not permit String Objects:-
These functions were part of the standard C library and it has been incorporated into the C++ library as well. To use these functions,if you are using an old C++ compiler, you should include the header file string.h. If you have a new C++ compiler that supports namespaces, then you should use the header <cstring>

Copying strings and concatenating strings:-
For copying we have a strcpy( ) function and for concatenation we have the strcat( ) function.

int main( )
{
char s1[20];
char s2[20];
strcpy(s1,"hi");
strcpy(s2,"bye");
strcat(s1,s2);
cout<<s1;
return 0;
}


The output is:

hibye

The function strcpy ( ) will act only on character arrays. Similarly the concatenation function strcat ( ) will also act only on two character arrays. You cannot create a string object and then use strcpy ( ).

string s1;
strcpy(s1,"hi");


will lead to an error (because s1 is not declared as a character array).

String length: This function will give you the length of the character array.

strlen(character-array)


String Comparison: 
The function will return an integer. The syntax for the function is:
 

int strcmp(char-array s1, char-array s2);
 

If s1>s2, then the result will be 1. If s1<s2, then the integer returned will be negative. If s1=s2, then the result will be 0.

There are many other functions that you might find useful but make sure as to whether you can create a string object or whether you have to work with character arrays. Depending on what you use, you will have different functions available.

0 comments:

Post a Comment