Strings

 

Strings are a collection of characters joint together. They are defined within double quotes. In order to include strings in C++ it is necessary to declare an additional header file <string>.

 

Syntax:

 

string name_of_the_string= "text"

 

Example:

 

#include <iostream>
#include <string>

using namespace std;

int main() 
{
  string str1 = "string";
  cout << str1;
  return 0;
}

 

Output:

string

 

Note: A string in C++ is actually an object, which contain functions that can perform certain operations on strings.

 

String Length

The length of a string is found using the length() function

 

Example:

 

#include <iostream>
#include <string>

using namespace std;

int main() 
{
  string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  cout << "The length of the txt string is: " << txt.length();
  return 0;
}

 

Access Characters of a string

 

We know that a string is an array of characters. Hence a particular character of a string can be accessed by the index number inside the square brackets[ ]. These signify the position of the character.

 

Example:

 

#include <iostream>
#include <string>

using namespace std;


int main() {
  string my_String = "Hello";
  cout << my_String[2];
  return 0;
}

 

Output: l //Which is the third element of the string

 

 

Alter string characters

 

Index numbers inside square brackets can be used to change string character.

 

Example

 

#include <iostream>
#include <string>

using namespace std;

int main() 
{
  string myString = "Food";
 myString[0] = 'G;
  cout << myString;
  return 0;
}

 

Output: Good //G replaced with F

 

Input a string from a User

 

Example:

string firstName;
cout << "Type your first name";
cin >>firstName;//Scaning a string
cout <<"Your first name is<<firstName;

 

Output:
 

Type your first name Geetanjali

Your first name is Geetanjali

 

Note: The cin function will only read a single word and the not multiple words. Hence only the first word will be displayed.

 

String Concatenation

'+' operator is used to add string together.

 

Example:

 

#include <iostream>
#include <string>

using namespace std;

int main () 
{
  string firstName = "Geetanjali";
  string lastName = "Purohit";
  string fullName = firstName + lastName;
  cout << fullName;
  return 0;
}

 

Output:

GeetanjaliPurohit

 

Note:

Results of Concatenation

 

Number + Number = Number

String + String = String

Number + String = Error