Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Different ways to copy a string in C/C++
Next article icon

Different ways to access characters in a given String in C++

Last Updated : 19 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character. There are several ways to access substrings and individual characters of a string. The string class supports the following functions for this purpose:

  1. operator[]
  2. at()
  3. substr()
  4. find()
  5. find_first_of()
  6. find_last_of()

Let's start discussing each of these methods in detail.

operator[]

operator[] returns the reference to the character at the position specified as the argument.

Syntax-

char& operator[](size_t pos);

Here, 
pos is the index of the character to be searched.

Below is the C++ program to implement the operator[] function-

C++
// C++ program to implement // the operator[] #include <iostream> using namespace std;  // Driver code int main() {     string str("GeeksforGeeks");     cout << str[4];     return 0; } 

Time Complexity : O(N)

Space Complexity : O(1)


Output
s

at()

at() function is used for accessing individual characters. With this function, character by character can be accessed from the given string.

Syntax-

char& string::at (size_type idx)

Below is the C++ to implement at()-

C++
// C++ program to implement // at() #include <iostream> using namespace std;  // Driver code int main() {     string s("GeeksForGeeks");     cout << s.at(4);     return 0; } 

Time Complexity : O(N)

Space Complexity : O(1)


Output
s


substr()

substr() function is used for retrieving a substring from a given string. This function takes two values start and len.

  • string.h is the header file required for string functions.
  • The starting index is 0.

Syntax-

string substr (size_type start, size_type len);

Here, 
start: Position of first character to be copied 
len: Length of the sub-string.

Below is the C++ program to implement the substr() function-

C++
// C++ program to implement // the substr() function #include <iostream> using namespace std;  // Driver code int main() {     string s("GeeksForGeeks");     cout << s.substr(1, 5);      return 0; } 

Output
eeksF

 

 

find()

find() function is used to find the first occurrence of a substring in the specified string being called upon.

  • It returns the index of the first occurrence of the substring in the string.
  • The default value of the starting position is 0.
  • If the substring is not found then the function returns -1.

Syntax-

size_t find (const string& str, size_t pos = 0);

size_t find (const char* s, size_t pos = 0);

Here, 
str is the substring to be searched.
s is the C-style substring to be searched.
pos is the initial position from where to start string search. The default value is 0.

Below is the C++ program to implement the find() function-

C++
// C++ program to implement // the find() function #include <iostream> using namespace std;  // Driver code int main() {     string s("GeeksForGeeks");     cout << s.find("For");      return 0; } 

Output
5

Time Complexity : O(N)

Space Complexity : O(1)


find_first_of()

find_first_of() function is used to find the first character that matches any of the characters specified in the arguments. This function takes two arguments str and pos. 

Syntax-

size_t find_first_of (const string& str, size_t pos = 0) const;

Here, 
str is the string with characters to search for.
pos is the position of the first character in the string to be considered for search.

Below is the C++ program to implement find_first_of() function-

C++
// C++ program to implement // the find_first_of() function #include <iostream> using namespace std;  // Driver code int main() {     string s("GeeksForGeeks");     cout << s.find_first_of('s');     return 0; } 

Output
4


find_last_of()

find_last_of() function is used for finding the location of last occurrence of the specified characters from the given string.

Syntax-

find_last_of(char ch);

find_last_of(char ch, size_t position);

Here, 
ch is the character to be searched in the string.
position is the index till where the search is to be performed.

Below is the C++ program to implement find_last_of() function-

C++
// C++ program to implement // the find_last_of() function #include <iostream> using namespace std;  // Driver code int main() {     string s("GeeksForGeeks");     cout << s.find_last_of('s');     return 0; } 

Output
12

Next Article
Different ways to copy a string in C/C++

C

codeutin
Improve
Article Tags :
  • Strings
  • C++
  • DSA
Practice Tags :
  • CPP
  • Strings

Similar Reads

  • Different ways to copy a string in C/C++
    Copying a string is a common operation in C/C++ used to create a duplicate copy of the original string. In this article, we will see how to copy strings in C/C++. Methods to Copy a String in C/C++1. Using strcpy() We can use the inbuilt function strcpy() from <string.h> header file to copy one
    15+ min read
  • Accessing characters by index in a String
    Given two strings str1 and an index, the task is to access the character at this index. Examples: Input: str = "hello", index = 1Output: e Input: str = "GfG", index = 2Output: G Accessing characters by index in a string:Individual characters in a string can be accessed by specifying the string name
    2 min read
  • Find one extra character in a string
    Given two strings which are of lengths n and n+1. The second string contains all the characters of the first string, but there is one extra character. Your task is to find the extra character in the second string. Examples: Input : string strA = "abcd"; string strB = "cbdae"; Output : e string B con
    15+ min read
  • iscntrl() in C++ and its application to find control characters
    In C++, iscntrl() is a predefined function used for string and character handling. cstring is the header file required for string functions and cctype is the header file required for character functions. A control character is one which is not a printable character i.e, it does not occupy a printing
    3 min read
  • Find last index of a character in a string
    Given a string str and a character x, find last index of x in str. Examples : Input : str = "geeks", x = 'e' Output : 2 Last index of 'e' in "geeks" is: 2 Input : str = "Hello world!", x = 'o' Output : 7 Last index of 'o' is: 7 Recommended PracticeLast index of a character in the stringTry It! Metho
    8 min read
  • Total length of string from given Array of strings composed using given characters
    Given a list of characters and an array of strings, find the total length of all strings in the array of strings that can be composed using the given characters.Examples: Input: string = ["mouse", "me", "bat", "lion"], chars = "eusamotb" Output: 10 Explanation: The strings that can be formed using t
    6 min read
  • Print the first and last character of each word in a String
    Given a string s consisting of multiple words, print the first and last character of each word. If a word contains only one character, print it twice (since the first and last characters are the same).Note: The string will not contain leading or trailing spaces. Examples: Input: s = "Geeks for geeks
    5 min read
  • Remove odd indexed characters from a given string
    Given string str of size N, the task is to remove the characters present at odd indices (0-based indexing) of a given string. Examples : Input: str = “abcdef”Output: aceExplanation:The characters 'b', 'd' and 'f' are present at odd indices, i.e. 1, 3 and 5 respectively. Therefore, they are removed f
    4 min read
  • Find the Nth occurrence of a character in the given String
    Given string str, a character ch, and a value N, the task is to find the index of the Nth occurrence of the given character in the given string. Print -1 if no such occurrence exists. Examples: Input: str = "Geeks", ch = 'e', N = 2 Output: 2 Input: str = "GFG", ch = 'e', N = 2 Output: -1 Recommended
    7 min read
  • 5 Different Methods to Find Length of a String in C++
    The string is a sequence of characters or an array of characters. The declaration and definition of the string using an array of chars are similar to the declaration and definition of an array of any other data type. Examples: Input: "Geeksforgeeks" Output: 13 Input: "Geeksforgeeks \0 345" Output: 1
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences