Access Strings
We can access the characters in a string by referring to its index number inside square brackets [].
Note: index starts from 0. [0] is the first character. [1] is the second character, etc.
Example:1
To print the first character of string:
string n = “Hello”;
cout << n[0];
// Outputs H
Example:2
To print the second character of string:
string n = “Hello”;
cout << n[1];
// Outputs e
//To access the elements of a string
#include<iostream>
#include<string>
using namespace std;
int main()
{
string n="Hello";
//1st character of string
cout<<n[0]<<endl;
//2nd character of string
cout<<n[1]<<endl;
//3rd character of string
cout<<n[2]<<endl;
//4th character of string
cout<<n[3]<<endl;
//5th character of string
cout<<n[4]<<endl;
return(0);
}
Output:
H
e
l
l
o
//To access the elements of a string
#include<iostream>
#include<string>
using namespace std;
int main()
{
string n="Hello";
for(int i=0;i<n.size();i++)
{
cout<<n[i]<<endl;
}
//By taking User input
cout<<"Enter any string ";
cin>>n;
for(int i=0;i<n.size();i++)
{
cout<<n[i]<<endl;
}
return(0);
}
Output:
H
e
l
l
o
Enter any string Computer
C
o
m
p
u
t
e
r




