String Handling in Cpp with Assignment
Though C++ has developed its own String data type still it support C style string that use totally array of characters to store single chars. A whole header file string.h is dedicated to handle different string operations.
In this tutorial, I will target on string handling using C++ but in C style as this is most relevant in Indian schools and colleges and this way they can better understand the process of character handling in C++.
Syntax of String Declaration
char stringName[size];
Valid Example of String
char name[30];
invalid declaration of String
char string[-30]; // negative size is not allowed
char string[0] ; // zero size is not allowed
char string [0..30]; // limits are also not allowed.
Inserting Value in String / Initialization of String
After decalation of any variable in C/C++ each and every variable is initialized with some garbage values. We need to fill that memory location with some useful information, we have to initialize that variable.
String initialization method -1
int string[40] = { ‘a’,’n’,u’,’\0’};
The last character is compulsory as per CPP documentation to tell compiler that it’s the end of our values in this string. This is call NULL.
String initialization method -2
int name = “Anu” ;
Explanation: Please note that in our previous initialization we used single quotation marks but in second initialization method we used Double quotation mark , in this case your compiler automatically insert NULL at the end of your value in that string.
String initialization method -3
char name[40];
name[0] =’a’;
name[1]=’n’;
name[2]=’u’;
name[3]=’\0’;
Explanation: Since in this case we are assigning single character to their respective position, we are required to set NULL value at the last position.
String initialization method -4 / Initialize string at run time using keyboard
Above string initialization methods were initializing your string at design time, using below method we can initialize string at run time
char name[30];
cin>>name;
Explanation: Please not in the above example we have not passed any index. Cin object is smart enough that it automatically enter each and every entered value inside your string unless until it meets ENTER KEY or SPACE BAR.
So if you try to enter ‘rakesh kumar’ in above string then it will only hold ‘rakesh’ not ‘kumar’ as there is space between these two words.
String initialization method -5
char name[40];
cin.getline(name,40);
Explanation: if you want to feed space inside your entered string value then this method is preferred method as this method will not terminate your value when it meets SPACE key.
String initialization method -5 ( This is from C Language)
char name[40];
gets(name);
Explanation: in order to use gets you are supposed to add stdio.h header file inside your program.
String initialization method -6
char string[] =”This is my first attempt in string handling”;
Explanation: Use this method only when you are declaring as well as initializing the array at the same time otherwise this method will through syntax error.
Output String Values on the screen
Now you know how you can insert values inside any string, before moving forward it would be a great help if we understand how we can display the value of string on the screen.
Display String – using manual method – Most useful method
This method is based on this fact that every string terminates with ‘\0’ and its first character always occupies first index start at zero.
Example
char string[ ] =”This is my first attempt in C++ string handling”;
int i=0;
while(string[i]!=’\0’){
cout<<string[i];
i++;
}
Explanation : Here we are comparing first element with NULL value if that is not NULL then display that value and increment your counter and repeat this loop till NULL.
Display String – Method -2
char string[] =”This is me and this is another example”
cout<<string;
Explanation: NOTE that this method also does not contain any string index, cout is smart enough to judge the last character of your string. Using this method you cannot print one character at a time.
Display String – Method -2
char string[] =”This is me and this is another example”
cout.write(string, 10);
The above method will print first 10 character of supplied string on the screen.
Some most common Question on String handling
Q1. Write a program in C++ to read a string from keyboard. Find out the total number of vowels available in that string.
Q2. Write a program in C++ to read a string from keyboard. Find out the total number of numbers available in that string.
Q2. Write a program in C++ to read a string from keyboard. Find out the total number of punctuation characters available in that string.
Q4. Write a program in c++ to read a string from keyboard. Find out total number of words available in this string and display the result on the screen.
Q5. Write a program in C++ to read a string from keyboard. Replace the occurrence of multiple spaces with single space and print this newly constructed string on the screen.
Q6. Write a program in C++ to read a string from keyboard. Check whether it is a valid ‘Identifier’ or not. Valid Identifier check program
These questions can be solved only if you are comfortable with the basics of Strings but there are a lots of functions available in string.h that make our life easier to manage string. Some of the widely used string functions are as follows
Strlen( ) – This function is used to find out total number of chars available in any string. Function accept string as a parameter and return total no of chars as an integer.
Example :
char string[] =”This is me”;
int n = strlen(string);
result : 10
Explanation : This function count even spaces as a chars thus produce 10.
strcpy( ) – This function copies the content of source string into target string. This function is one of the most important function as string does not support regular assignment operator(=)
Example
int main() {
char source[40] =”Hello anushka”;
char target[90];
strcpy(source, target);
cout<<”\n Copied string :”<<target; return 0; }
Result: Copied string: Hello anushka
strcmp( ) – This is another very important function as string does not support relational operator like >, <,==, >= , <=, != so in all these situations we have to use strcmp function. This function compare two string values based on their ascii code and return an integer value
Example :1
char first[40] =”amit”;
char second[40]=”sumit”;
int n = strcmp(first,second);
result : n will contain a negative value, it means first string is smaller than second string
Example :2
char first[40] =”amit”;
char second[40]=”sumit”;
int n = strcmp(second,first);
result : n will contain a positive negative value. It means second string is greater than first string
Example :3
char first[40] =”amit”;
char second[40]=”sumit”;
int n = strcmp(first,first);
result : n will contain a ZERO value. It means both strings are equal.
Another common and most used string functions are listed below
S.No | Function | Explanation |
1. | strlwr() | Convert any UPPER case string into lower case string
Example : char string[] =”HELLO NISHAL” strrev(string); cout<<string; Result: hello nishcal |
2. | strupr() | Convert any lowercase string into UPPERCASE string
Example: char string[] =”this is string” strupr(string); cout<<string; result: THIS IS STRING |
3. | Strrev() | Reverse the order of string contents
Example: char string[] =”Hi rakesh”; strrev(string); cout<<string; Result: hsekar iH |
For more string related built in functions, You are requested to kindly check string.h header file or CPP documentation.
Array of String / Double Dimension of chars
Array of string can be defined the same way we used to define our double dimensional array. In this case each row will contain a single string and that string will be further divided into NULL (‘\0’) terminated string.
Syntax of Double Dimensional String
char stringName[row][column];
Example :
Suppose we want to store the name of 10 students in an array of string. Each name could have maximum 40 characters. SO the definition could be
char name[10][40];
How to feed data into array of string / Initialization Methods
There are again multiple methods to enter values in array of string. Here I have listed only most used methods.
Method – 1
char name[5][30] = { {‘a’,’n’,’u’,’\0’}, {‘s’,’u’,’r’,’e’,’s’,’h’,’\0’},{‘d’,’h’,’a’,’n’,’u’,’\0’},{‘u’,’d’,’I’,’t’,’\0’},{‘u’,’t’,’s’,’a’,’v’,’\0’’}};
Method-2
char name[5][30] ={“anu”,”Suresh”,”dhanu”,”udit”,”utsav”};
Method-3 : only applicable when you are initializing at the time of declaration
char name[ ][30] ={“anu”,”Suresh”,”dhanu”,”udit”,”utsav”};
Method -4
char name[5][30];
strcpy(name[0],”anu”);
strcpy(name[1],”suresh”);
strcpy(name[2],”Dhanu”);
strcpy(name[3],”udit”);
strcpy(name[4],”Utsav”);
Method – 5 – At run time from keyboard
char name[5][30];
for(i=0;i<5;i++)
cin>>name[i]; // here you can any input method that either terminate SPACE or cin.getline() that does not terminate string on SPACE.
Assignment Based on ARRAY of string
Q1. Write a program in C++ to read an array of string to store 10 Name of class 11th student. Find out whether a name “Rajul” exists in this array or not.
Q2. Writ a program in C++ to read 10 cities name in an array of string. Arrange these names in ascending order. Also display this arranged array on the screen.