String operationsConcatenation and Comparing Strings

String operations in C++ are performed using some of the same operators that are used for arithmetic operations. The symbols are interpreted slightly differently in some cases. We've already seen the use of the = operator for assignment. 

Concatenating Strings:
It is possible to join two or more strings together using the + operator. Rather than addition, this use of the + operator joins one string to the end of another; this operation is called concatenation.
string str1, str2, str3;
str1 = "yesterday";
str2 = "morning";
str3 = str1+ " " + str2;
cout << str3 << endl; 
String str3 has the value "yesterday morning", and that value is sent to cout. 
Notes:
• It is necessary to concatenate a space between the two words to produce a space in the resulting string.  
• At least one of the operands must be a variable. [Useless to concatenate two literals.]
• The use of an operator (like +) for two different actions is called operator overloading. [not responsible this term]
string str = "train"; 
str = str + 's';
str has the value "trains". 
Note that it is also possible to use the += operator to perform concatenation:
str += 's';

Comparing Strings
You can compare two strings using the standard relational operators (<, <=, >, >=, ==, and !=). Two strings are the same (equal to each other) if they have the same number of characters and if each corresponding character matches: e.g., "cat" is the same as "cat" but not the same as "act", "Cat" or even as "cat " (with a space at the end). 
string str1 = "cat";
string str2 = "dog";
if (str1 == str2)
cout << "alike" << endl;
else
cout << "different" << endl;
   
This will, of course, print "different"  because "cat" is not the same string as "dog".  
Strings can be compared to determine whether one is greater than or less than the other. 
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: