Accessing character elements from a string in C++ STL

C++ STL | accessing a character from a string: In this article we are going to see how we can access character elements of the string?
Submitted by Radib Kar, on February 27, 2019

String as datatype

In C, we know string basically a character array terminated by \0. Thus to operate with the string we define character array. But in C++, the standard library gives us the facility to use the string as a basic data type like an integer. But the string characters can be still accessed considering the string as a character array.

Example:

    Like we define and declare,

    string s="IncludeHelp";
    s[0] = 'I' (not "I")
    s[7] = 'H' 
    
    //So same way we can access the string element which is character.
    //Also there is a function under string class, at(), 
    //which can be used for the same purpose.
    cout << s.at(7); //prints H

Remember, a string variable (literal) need to be defined under "". 'a' is a character whereas "a" is a string.

Note: Trying to accessing character beyond string length results in segmentation fault.

Header file needed:

    #include <string>
    Or
    #include <bits/stdc++.h>

C++ program to demonstrate example of accessing characters of a string

#include <bits/stdc++.h>
using namespace std;

int main(){
	string s;
	
	cout<<"enter string...\n";
	cin>>s;
	
	cout<<"Printing all character elements...\n";
	for(int i=0;i<s.length();i++)
		cout<<s[i]<<" ";
	
	return 0;
}

Output

enter string...
IncludeHelp
Printing all character elements...
I n c l u d e H e l p



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.