String: " A combination of Characters is called String".
Representation:
Two types
- C-style type character string
- String class type
C-style Character String:
"One dimensional array of characters followed by null character."Basically a null terminated string.
==> Null Character: It is represented by " \0 ".
This null character is used at the end of every string. It means when you defined array for strings then array size must be greater than number of characters in strings.
Example:
Example:
char x[6] = {'N','O','U','M','A','N','\0'};
On the other hand if you look at the array initialization , it can also be defined like this
char x[]="NOUMAN";
Program code:
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
char MY_NAME[7]={'N','O','U','M','A','N','\0'};
cout<<"MY NAME IS = "<<MY_NAME;
getch ();
}
Output:
Functions For Strings:
C++ supports wide variety of functions having different properties to deal with Strings.Some of them are given below.
Note: To use these functions don't forget to include library ==> #include<cstring>
- strcpy( str1,str2 ); ==> Copies string 2 to string 1.
- strlen(str1); ==> Gives the length of string 1.
- strcmp(str1,str2); ==> Do comparison. if equal result = 0 , if str2 is greater than str1 result > 0 , if str2 is smaller than str1 then result < 0
- strcat(str1,str2); ==> Concatenates string 1 and string 2.
Example:
Lets do an example on this
Program code:
#include<iostream>
#include<conio.h>
#include<cstring>
using namespace std;
int main()
{
int length ,compare;
char str1[10]="Nouman";
char str2[]="Mustafa";
char str3[10];
strcpy (str3,str1); // copies str1 to str3
compare = strcmp(str1,str2); // compares str 1 and str 2
length = strlen(str1); // determines the length of str1
cout<<"result of function strcpy is = "<< str3 <<endl<<endl;
cout<<"Comparison = "<< compare <<endl<<endl;
cout<<"length of string 1 is = "<< length <<endl<<endl;
getch ();
}
Output: After compilation and execution of above program result is ..
Click to enlarge it.
Keep practicing on it.
strcpy(n," "); i not working
ReplyDeleteplease help
Thanks
ReplyDelete