Home » C++ STL

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

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.