Strings in C++

Notes:

Strings in C++ Programming Language:

String:
- is a single character or sequence (or array) of characters enclosed in between pair of double quotations
Ex: “A”, “Hello World”, “123” etc.

Syntax for declaring and initializing a char type array:
char arrayName[size] = “sequence of characters”;
where: size must be total number of characters available in a given string + 1; because a string in C++ language is implicitly terminated with an extra character called as null ( ‘\0’ ) character
Ex:
char player1Name[7] = ”Ramesh”;

OR

Syntax for declaring and initializing a pointer to a string:
char *pointerVariableName = “sequence of characters”;
Ex:
char *player2Name =”Suresh”;

OR

Syntax for declaring and initializing a string type variable:
string variableName = “sequence of characters”;
Ex:
string player3Name =”Viresh”;

Note: you must include string header file to use string type

Example code:

#include <iostream>
#include<string>

using namespace std;

int main()
{
/*
char player1Name[7] = "Ramesh";
cout << "player1 name = " << player1Name << endl; // Ramesh
cout << player1Name[0] << endl; // R
cout << player1Name[1] << endl; // a

char *player2Name = "Suresh";
cout << "player2 name = " << player2Name << endl; // Suresh
cout << *(player2Name + 0) << endl; // S
cout << *(player2Name + 1) << endl; // u
*/

string player3Name = "Viresh";
cout << "player3 name = " << player3Name << endl; // Viresh
cout << player3Name[0] << endl; // V
cout << player3Name[1] << endl; // i
cout << player3Name[2] << endl; // r

return 0;
}