C++ Strings 
Different from C strings
Flush Everything you knew about C 
strings
Declare a string 
#include<iostream> 
using namespace std; 
int main() 
{ 
string a; 
//Declare a string 
cin>>a; 
cout<<a<<endl; 
}
Initialize a string 
string a=“Welcome to strings”;
Inputing strings having spaces 
string a; 
getline(cin,a);
Copy a String 
//No need for strcpy 
string a,b; 
cin<<a; 
b=a; 
cout>>b>>endl;
Concatenate two string 
string a,b,c; 
cin>>a>>b; 
c=a+b; 
//Is’nt life easy 
cout<<c<<endl;
Length of a string 
string a; 
cin>>a; 
cout<<a.length()<<endl; 
cout<<a.size()<<endl; 
//Be little careful the value is not integer
Reverse a String 
Input – abcde 
Output- edcba
Some String properties 
• Strings are zero indexed just like arrays. 
• Each individual element of a string is a 
character.(char datatype)
Palindrome?
Memory 
• Every variable you declare takes some amount 
of memory 
• Just think of memory as a free store and every 
time you declare a variable you allocate some 
space in that free store. 
• Example Integer takes 4 bytes,Character takes 
1 byte.
Do we need to memorize this? 
• Use the sizeof() operator 
• Tells you the number of bytes allocated to a 
datatype or a variable 
• Example-sizeof( 
int) 
char c; 
sizeof(c);
Dynamic Memory Allocation 
• Sometimes you do not the amount of memory 
you would be needing.
The new operator
The delete operator
Example
Dynamic Memory allocation for arrays
You have been given a grid of n 
rows of m integers. Input n and m 
and dynamically allocate the array 
and take the array as input and 
print the grid as given.

Lecture 3: Strings and Dynamic Memory Allocation