String in C++ language:
In C++ language, String is a collection of character or group of character. But in C language string is used by array character. As we know string in C language is a one-dimensional array of character which is terminated by a null character '\0'. On the other hand, In C++ language, String is a collection of character which is enclose between double cotes ( " " ). Character is enclosed within single quotes in C language, but Strings in C++ are always enclosed within double quotes.
Declaration of String in C++ language:
As we know, Strings are declared in C in similar manner as arrays but the only difference is that it is of char type. During the declaration of string, size must be required to mention otherwise it gives an error message. The string size must be unsigned integer value, which is greater than zero only.
Syntax of string declaration:
char variable_name[SIZE];
Examples of string declaration:
char str1[10]; // Valid string
char str2[]; // Invalid string
char str[0]; // Invalid string
char str[-1]; // Invalid string
Examples on initializing Array string in C++ programming:
1. char str1[]="xyza";
2. char str2[5]="xyza";
3. char str3[5]={'x','y','z','a','\0'};
4. char str4[]={'x','y','z','a','\0'};
Important points which should be remembered for initialization of the string in C++ language:
1. Uninitialized size of the string is initialized with NULL value. i.e char str[6] = {'x','y','z','a','\0'}, in this example the value of str[6] is equal to NULL.
2. String can not initialized more than size of string elements. i.e char str[4] = {'x','y','z','a','\0'}, here we get a compile time error.
3. During initialization of the string the size is optional, but in this case the array size became equal to the total element stored into the string array. i.e. char str4[]={'x','y','z','a','\0'};
4. When we are working with character array explicitly NULL character does not occupies any physical memory at the end of the character array but String data at the end of the string NULL character occupies physical memory.
All the library function of String is available in String.h header file.
1 strcpy(s1, s2) : Copies string s2 into string s1.
2 strcat(s1, s2) : Concatenates string s2 onto the end of string s1.
3 strlen(s1) : Returns the length of string s1.
4 strcmp(s1, s2) : Returns 0 if s1==s2; < 0 if s1<s2; >0 if s1>s2.
5 strchr(s1,ch) : Returns a pointer to the first occurrence of ch in string s1.
6 strstr(s1, s2) : Returns a pointer to the first occurrence of string s2 in string s1.
Thanks
Mukesh Rajput
Post A Comment:
0 comments: