Just like a group of integers can be stored in an integer array. Similarly, a group of characters can also be stored in a character array. This array of characters is known as a string. Strings are used for storing and manipulating text such as words and sentences.
A string in C++ is a collection of characters terminated by a null character (‘\0’), specifying where the string terminates in memory. A string can be represented as a one-dimensional char type array where each string’s character is stored as an element of the array. For example: “Try Again” is a string constant stored in memory, as shown below figure.
Each element of the string is stored in a contiguous memory location and terminated by a null character (‘\0’) which is automatically inserted by the compiler to indicate the string’s end.
A string constant is always enclosed in double quotes (” “) and may include alphabets, numbers, escape sequence, blank space and special characters etc. Some of the valid string constants are “Good morning” , “27”, ” “, “41-B”, “121+31-43” and “B”.
Defining and Initializing String Variables
The strings are an array of characters, so they are defined as
char array_name[size];
where array_name is the name of the string, and size represents the maximum number of characters that can be stored, and it must be a positive integer value. Consider an example
char name[30];
It defines an array name and reserves 30 bytes for storing characters as a single character consumes 1 byte. The last byte is used for storing the null character ‘\0’, so the total number of the character specified by the user cannot exceed 29.
#include<iostream.h> #include<conio.h> int main() { clrscr(); char name[20]; cout<<"Enter the nameof the person :\n"; cin>>name; cout<<"Name entered was :"<<name; getch(); return 0; } Output Enter the name of the person Dinesh Name entered was : Dinesh
Explanation: The above program inputs and displays the name of a person. The statement
cin>>name;
prompts the user to enter the name. The user should make sure that name should not exceed 19 characters as the last character is reserved for ‘\0’. Finally, the statement cout<<name; displays the contents of the character array name on the screen.
Strings can also be initialized. The following example shows different ways of initializing a string.
char name[7] ="DINESH; or char name [7]={ 'D', 'I', 'N', 'E', 'S', 'H', '\0'}; or char name[]="DINESH";
In the first method of initialization, the compiler allocates space for 7 characters for array name. The first six characters are filled with D, I, N, E, S, H characters and ending with a character ‘\0’ (null character) automatically. So it will appear in memory as follows,
The second method of initialization also copies the individual characters into the array name in the same way as in the previous initialization, except that the user has to explicitly specify the null character (‘\0’) to mark the end of the character array so that it can be used as a string.
However, if the user specifies the array size to be less than the number of characters during initialization, it may give you unpredictable results. For example
char name[6]={ 'D', 'I', 'N', 'E', 'S', 'H', '\0'};
In the above initialization, as there is no space in the character array for storing null character (‘\0’), it makes the array unusable as a string that causes unpredictable results during the program’s execution.
So, the above problem can be overcome by specifying the size large enough to hold all the string characters, including the null character (‘\0’). As it is always difficult to count for the exact size, so a rough approximation should follow. For example
char name[10]="DINESH";
In the above initialization, the compiler allocates space for 10 characters, where the first 7 characters are filled with D, I, N, E, S, H and end with \0. The remaining 3 spaces of the character array are filled with null characters (‘\0’) automatically—this method of initialization results in wastage of memory.
A better method of initialization is to skip the character array’s size at the time of its initialization. In such a case, the compiler automatically computes its size.
char name[] = "DINESH";
The compiler sets aside memory for 7 characters for character array name large enough to store all the characters, including null character. This initialization method is useful in situations where the initialized string is very long, as calculating the length manually can be error-prone.
#include<iostream.h> #include<conio.h> int main() { char name []="Hello"; cout<<"strinG = "<<name; return 0; } Output : String = Hello
Inputting Multi-Word String
When you input a multi-word string using an extraction operator used with cin, it reads characters until it encounters a white space character and ignores the subsequent characters.
#include<iostream.h> int main() { char name[20]; cout<<"Enter name = "; cin>>name; cout<<"Name of person = "<<name; return 0; } Output Enter name = Dinesh Thakur Name of person = Dinesh
The required output is not displayed as the compiler ignores the characters after the first space. Thus, the multi-word string cannot be inputted using an >> operator in association with cin.
So to read multi-word string, use cin.get().
#include<iostream.h> #include<conio.h> int main() { clrscr(); char name[20]; cout<<"Enter name = "; cin.get(name,20); cout<<"Name of Person = "<<name; return 0; } Output : Enter name = Dinesh Thakur Name of Person = Dinesh Thakur
Explanation: In the above program, we get the expected output. The function cin.get() takes two arguments. The first corresponds to the array name, and the second corresponds to the maximum number of characters inputted. The user can input a multi-word string until the maximum number of characters is 19 (one reserved for ‘\0’) or the user enters a new line character (‘\n’).
Now let us consider another program
// Program to count frequency of vowels in a string #include <iostream.h> #include <conio.h> #include <string.h> int main() { clrscr(); char str[80]; int i,len,acount,icount,ecount,ocount,ucount; cout<<"Enter the string -->"; cin.get(str,80); len = strlen(str); acount=icount=ecount=ocount=ucount=0; for(i=0;i<len;i++) { if(str[i]=='a') acount++; else if(str[i]=='e') ecount++; else if(str[i]=='i') icount++; else if(str[i]=='o') ocount++; else if(str[i]=='u') ucount++; } cout<<"a occurs "<<acount<<" times\n"; cout<<"e occurs "<<ecount<<" times\n"; cout<<"i occurs ''<<icount<<" times\n"; cout<<"o occurs "<<ocount<<" times\n"; cout<<"u occurs "<<ucount<<" times\n"; getch(); return 0; } Output: Enter the string -->welcome india a occurs 1 times e occurs 2 times i occurs 2 times o occurs 1 times u occurs 0 times
Inputting Multi-Line String
Like multi-word strings, users can also input multi-line strings using the cin.get( ) function with little modification. It takes the following form.
get(str, MAX, delim)
Here, str is an array of characters. MAX is the maximum number of characters, and delim is the delimiter character that specifies when to stop reading. This function reads characters from the keyboard, stored in array str until either (MAX-1) characters have been read or a character specified by delim has been found.
#include<iostream.h> #include<conio.h> int main() { clrscr(); char str[80]; cout<<"Enter a string : \n"; cin.get(str,80,'*'); cout<<"String =\n"<<str; return 0; } Output : Enter a string : Share Index is growing. Buy IPCI at current price*. String= Share Index is growing Buy IPCI at current price
Another way to input multi-line strings is by using the getline function. This function is similar to that of get (str, MAX, delim) for inputting multi-line strings except that it removes the delimiter character from the input stream, whereas, in the case of get, it remains in the input stream until the next input operation.
Consider the following program segment.
char str[80]; cin.getline(str,80, '*');
This statement on execution can input multiple lines until either user enters the terminating character ‘*’ or until the user exceeds the size of the array.
The getline() is preferred over get() because it discards the delimiter rather than leaving it in the input stream until the next input operation.
#include <iostream.h> #include <conio.h> int main() { clrscr(); char a[100]; int c=0,w=1,l=1; cout<<"Enter the string ;"; cin.getline(a,100,'*'); for(int i=0;a[i]!='\0';i++) { if (a[i]='\n') {l++;w++;} if(a[i]==' ' && a[i+1] !=' ') w++; c++; } cout<<"Characters = "<<c; cout<<"\nWords ="<<w; cout<<"\nLines = "<<l; getch(); return 0 ; } Output : Enter' the string : My Name is Movis My House number is 6886* Characters = 40 Words = 9 Lines = 2
Explanation: In this program, we input multiple lines of a string using the cin.getline() function. Then we traverse each character of the string one by one. On encountering any space between two consecutive characters, word count w is incremented by 1. Similarly, for line count 1. Finally, count for words, characters and lines are displayed. We initialize w = 1 and 1 = 1 as we assume that each string has atleast one word and one line.