- A Brief Intro To C++ & Its History
- The Detailed History & Timeline Of C++ (With Infographic)
- Importance Of C++
- Versions Of C++ Language
- Structure Of A C++ Program
- Comparison With Other Popular Programming Languages
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Are Variables In C++?
- Declaration & Definition Of Variables In C++
- Variable Initialization In C++
- Rules & Regulations For Naming Variables In C++ Language
- Different Types Of Variables In C++
- Different Types of Variable Initialization In C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Are Primitive Data Types In C++?
- Derived Data Types In C++
- User-Defined Data Types In C++
- Abstract Data Types In C++
- Data Type Modifiers In C++
- Declaring Variables With Auto Keyword
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- Structure Of C++ Program: Components
- Segment 1: Documentation Section Of Structure Of C++ Program (With Example)
- Segment 2: Preprocessing & Namespace (Linking) Section Of CPP Program
- Segment 3: Definition Section In Structure of a C++ Program (With Examples)
- Segment 4: Main Function In Structure Of A C++ Program (With Example)
- Compilation & Execution Of C++ Programs | Step-by-Step Explanation
- Explaining Structure Of C++ Program With Suitable Example
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What is Typedef in C++?
- The Role & Applications of Typedef in C++
- Basic Syntax for typedef in C++
- How Does typedef Work in C++?
- How to Use Typedef in C++ With Examples? (Multiple Data Types)
- The Difference Between #define & Typedef in C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Are Strings In C++?
- Types Of Strings In C++
- How To Declare & Initialize C-Style Strings In C++ Programs?
- How To Declare & Initialize Strings In C++ Using String Keyword?
- List Of String Functions In C++
- Operations On Strings Using String Functions In C++
- Concatenation Of Strings In C++
- How To Convert Int To Strings In C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is String Concatenation In C++?
- How To Concatenate Two Strings In C++ Using The ‘+' Operator?
- String Concatenation Using The strcat( ) Function
- Concatenation Of Two Strings In C++ Using Loops
- String Concatenation Using The append() Function
- C++ String Concatenation Using The Inheritance Of Class
- Concatenate Two Strings In C++ With The Friend and strcat() Functions
- Why Do We Need To Concatenate Two Strings?
- How To Reverse Concatenation Of Strings In C++?
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is Find In String C++?
- What Is A Substring?
- How To Find A Substring In A String In C++?
- How To Find A Character In String C++?
- Find All Substrings From A Given String In C++
- Index Substring In String In C++ From A Specific Start To A Specific Length
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Are Pointers In C++?
- Pointer Declaration In C++
- How To Initialize And Use Pointers In C++?
- Different Types Of Pointers In C++
- References & Pointers In C++
- Arrays And Pointers In C++
- String Literals & Pointers In C++
- Pointers To Pointers In C++ (Double Pointers)
- Arithmetic Operation On Pointers In C++
- Advantages Of Pointers In C++
- Some Common Mistakes To Avoid With Pointers In Cpp
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- Understanding Pointers In C++
- What Is Pointer To Object In C++?
- Declaration And Use Of Object Pointers In C++
- Advantages Of Pointer To Object In C++
- Pointer To Objects In C++ With Arrow Operator
- An Array Of Objects Using Pointers In C++
- Base Class Pointer For Derived Class Object In C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is 'This' Pointer In C++?
- Defining ‘this’ Pointer In C++
- Example Of 'this' Pointer In C++
- Describing The Constness Of 'this' Pointer In C++
- Important Uses Of 'this' Pointer In C++
- Method Chaining Using 'this' Pointer In C++
- C++ Programs To Show Application Of 'This' Pointer
- How To Delete The ‘this’ Pointer In C++?
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What is Reference?
- What is Pointer?
- Comparison Table Of C++ Pointer Vs. Reference
- Differences Between Reference And Pointer: A Detailed Explanation
- Why Are References Less Powerful Than Pointers?
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- How To Declare A 2D Array In C++?
- C++ Multi-Dimensional Arrays
- Ways To Initialize A 2D Array In C++
- Methods To Dynamically Allocate A 2D Array In C++
- Accessing/ Referencing Two-Dimensional Array Elements
- How To Initialize A Two-Dimensional Integer Array In C++?
- How To Initialize A Two-Dimensional Character Array?
- How To Enter Data In Two-Dimensional Array In C++?
- Conclusion
- Frequently Asked Questions
- What Are Arrays Of Strings In C++?
- Different Ways To Create String Arrays In C++
- How To Access The Elements Of A String Array In C++?
- How To Convert Char Array To String?
- Conclusion
- Frequently Asked Questions
- What is Memory Allocation in C++ & Why Do We Need It?
- How Does Dynamic Memory Allocation Work?
- The new Operator in C++
- The delete Operator in C++
- Dynamic Memory Allocation in C++ | Arrays
- Did You Know: Companies That Ask About Dynamic Memory Allocation
- Dynamic Memory Allocation in C++ | Objects
- Deallocation of Dynamic Memory in C++
- malloc(), calloc(), and free() Functions in C/C++
- Applications of Dynamic Memory Allocation in C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is A Substring In C++ (Substr C++)?
- Example for substr() in C++ | Finding Substring Using Positive and Negative Indices
- Understanding substr() Basics with Examples
- Use Cases/ Examples of substr() in C++
- How to Get a Substring Before a Character Using substr() in C++?
- Use substr() in C++ to Print all Substrings of a Given String
- Print Sum of all Substrings of a String Representing a Number
- Minimum Value of all Substrings of a String Representing a Number
- Maximum Value of all Substrings of a String Representing a Number
- Points To Remember For Substr In C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is Operator In C++?
- Types Of Operators In C++ With Examples
- What Are Arithmetic Operators In C++?
- What Are Assignment Operators In C++?
- What Are Relational Operators In C++?
- What Are Logical Operators In C++?
- What Are Bitwise Operators In C++?
- What Is Ternary/ Conditional Operator In C++?
- Miscellaneous Operators In C++
- Precedence & Associativity Of Operators In C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is The New Operator In C++?
- Example To Understand New Operator In C++
- The Grammar Elements Of The New Operator In C++
- Storage Space Allocation
- How Does The C++ New Operator Works?
- What Happens When Enough Memory In The Program Is Not Available?
- Initializing Objects Allocated With New Operator In C++
- Lifetime Of Objects Allocated With The New Operator In C++
- What Is The Delete Operator In C++?
- Difference Between New And Delete Operator In C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- Types Of Overloading In C++
- What Is Operator Overloading In C++?
- How To Overload An Operator In C++?
- Overloadable & Non-overloadable Operators In C++
- Unary Operator Overloading In C++
- Binary Operator Overloading In C++
- Special Operator Overloading In C++
- Rules For Operator Overloading In C++
- Advantages And Disadvantages Of Operator Overloading In C++
- Function Overloading In C++
- What Is the Difference Between Operator Functions and Normal Functions?
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Are Operators In C++?
- Introduction To Logical Operators In C++
- Types Of Logical Operators In C++ With Example Program
- Logical AND (&&) Operator In C++
- Logical NOT(!) Operator In C++
- Logical Operator Precedence And Associativity In C++
- Relation Between Conditional Statements And Logical Operators In C++
- C++ Relational Operators
- Conclusion
- Frequently Asked Important Interview Questions:
- Test Your Skills: Quiz Time
- Different Type Of C++ Bitwise Operators
- C++ Bitwise AND Operator
- C++ Bitwise OR Operator
- C++ Bitwise XOR Operator
- Bitwise Left Shift Operator In C++
- Bitwise Right Shift Operator In C++
- Bitwise NOT Operator
- What Is The Meaning Of Set Bit In C++?
- What Does Clear Bit Mean?
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- Types of Comments in C++
- Single Line Comment In C++
- Multi-Line Comment In C++
- How Do Compilers Process Comments In C++?
- C- Style Comments In C++
- How To Use Comment In C++ For Debugging Purposes?
- When To Use Comments While Writing Codes?
- Why Do We Use Comments In Codes?
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Are Storage Classes In Cpp?
- What Is The Scope Of Variables?
- What Are Lifetime And Visibility Of Variables In C++?
- Types of Storage Classes in C++
- Automatic Storage Class In C++
- Register Storage Class In C++
- Static Storage Class In C++
- External Storage Class In C++
- Mutable Storage Class In C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- Decision Making Statements In C++
- Types Of Conditional Statements In C++
- If-Else Statement In C++
- If-Else-If Ladder Statement In C++
- Nested If Statements In C++
- Alternatives To Conditional If-Else In C++
- Switch Case Statement In C++
- Jump Statements & If-Else In C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is A Switch Statement/ Switch Case In C++?
- Rules Of Switch Case In C++
- How Does Switch Case In C++ Work?
- The break Keyword In Switch Case C++
- The default Keyword In C++ Switch Case
- Switch Case Without Break And Default
- Advantages & Disadvantages of C++ Switch Case
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is A For Loop In C++?
- Syntax Of For Loop In C++
- How Does A For Loop In C++ Work?
- Examples Of For Loop Program In C++
- Ranged Based For Loop In C++
- Nested For Loop In C++
- Infinite For Loop In C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is A While Loop In C++?
- Parts Of The While Loop In C++
- C++ While Loop Program Example
- How Does A While Loop In C++ Work?
- What Is Pre-checking Process Or Entry-controlled Loop?
- When Are While Loops In C++ Useful?
- Example C++ While Loop Program
- What Are Nested While Loops In C++?
- Infinite While Loop In C++
- Alternatives To While Loop In C++
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Are Loops & Its Types In C++?
- What Is A Do-While Loop In C++?
- Do-While Loop Example In C++ To Print Numbers
- How Does A Do-While Loop In C++ Work?
- Various Components Of The Do-While Loop In C++
- Example 2: Adding User-Input Positive Numbers With Do-While Loop
- C++ Nested Do-While Loop
- C++ Infinitive Do-while Loop
- What is the Difference Between While Loop and Do While Loop in C++?
- When To Use A Do-While Loop?
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What are 2D Vectors in C++?
- How to Declare 2D Vectors in C++
- How to Initialize a 2D Vector in C++?
- Creating a 2D Vector in C++ with User Input for Column & Row Size
- Methods for Traversing 2D Vectors in C++
- Interview Spotlight: 2D Vectors in FAANG Interviews
- Printing 2D Vector in C++ Using Nested Loops
- Example C++ Programs for Creating 2D Vectors
- How to Access & Modify 2D Vector Elements in C++?
- Adding Elements to 2D Vector Using push_back() Function
- Removing Elements from Vector in C++ Using pop_back() Function
- Did You Know? Real-World Outage: Crash Cause Linked to 2D Vector Usage
- Advantages of 2D Vectors Over Traditional Arrays
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- How To Print A Vector In C++ By Overloading Left Shift (<<) Operator?
- How To Print Vector In C++ Using Range-Based For-Loop?
- Print Vector In C++ With Comma Separator
- Printing Vector In C++ Using Indices (Square Brackets/ Double Brackets & at() Function)
- How To Print A Vector In C++ Using std::copy?
- How To Print A Vector In C++ Using for_each() Function?
- Printing C++ Vector Using The Lambda Function
- How To Print Vector In C++ Using Iterators?
- Conclusion
- Frequently Asked Questions
- Definition Of C++ Find In Vector
- Using The std::find() Function
- How Does find() In Vector C++ Function Work?
- Finding An Element By Custom Comparator Using std::find_if() Function
- Use std::find_if() With std::distance()
- Element Find In Vector C++ Using For Loop
- Using The find_if_not Function
- Find Elements With The Linear Search Approach
- Conclusion
- Frequently Asked Questions
- What Is Sort() Function In C++?
- Sort() Function In C++ From Standard Template Library
- Exceptions Of Sort() Function/ Algorithm In C++
- The Stable Sort() Function In C++
- Partial Sort() Function In C++
- Sorting In Ascending Order With Sort() Function In C++
- Sorting In Descending Order With Sort Function In C++
- Sorting In Desired Order With Custom Comparator Function & Sort Function In C++
- Sorting Elements In Desired Order Using Lambda Expression & Sort Function In C++
- Types of Sorting Algorithms In C++
- Advanced Sorting Algorithms In C++
- How Does the Sort() Function Algorithm Work In C++?
- Conclusion
- Frequently Asked Questions
- What Is Function Overloading In C++?
- Ways Of Function Overloading In C++
- Function Overloading In C++ Using Different Types Of Parameters
- Function Overloading In C++ With Different Number Of Parameters
- Function Overloading In C++ Using Different Sequence Of Parameters
- How Does Function Overloading In C++ Work?
- Rules Of Function Overloading In C++
- Why Is Function Overloading Used?
- Types Of Function Overloading Based On Time Of Resolution
- Causes Of Function Overloading In C++
- Ambiguity & Function Overloading In C++
- Advantages Of Function Overloading In C++
- Disadvantages Of Function Overloading In C++
- Operator Overloading In C++
- Function Overriding In C++
- Difference Between Function Overriding & Function Overloading In C++
- Conclusion
- Frequently Asked Questions
- What Is An Inline Function In C++?
- How To Define The Inline Function In C++?
- How Does Inline Function In C++ Work?
- The Need For An Inline Function In C++
- Can The Compiler Ignore/ Reject Inline Function In C++ Programs?
- Normal Function Vs. Inline Function In C++
- Classes & Inline Function In C++
- Understanding Inline, __inline, And __forceinline Functions In C++
- When To Use An Inline Function In C++?
- Advantages Of Inline Function In C++
- Disadvantages Of Inline Function In C++
- Why Not Use Macros Instead Of An Inline Function In C++?
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is Static Data Member In C++?
- How To Declare Static Data Members In C++?
- How To Initialize/ Define Static Data Member In C++?
- Ways To Access A Static Data Member In C++
- What Are Static Member Functions In C++?
- Example Of Member Function & Static Data Member In C++
- Practical Applications Of Static Data Member In C++
- Conclusion
- Frequently Asked Questions
- What Is A Constant In C++?
- Ways To Define Constant In C++
- What Are Literals In C++?
- Pointer To A Constant In C++
- Constant Function Arguments In C++
- Constant Member Function Of Class In C++
- Constant Data Members In C++
- Object Constant In C++
- Conclusion
- Frequently Asked Questions(FAQ)
- What is the Friend Function in C++?
- Declaration of Friend Function in C++ with Example
- Characteristics of Friend Function in C++
- Types/ Ways to Implement Friend Function in C++
- Global Friend Function in C++ (Global Function as Friend Function )
- Member Function of Another Class as a Friend Function in C++
- Function Overloading Using Friend Function in C++
- Advantages & Disadvantages of Friend Function in C++
- Interview Spotlight: Friend Functions in Cognizant Interview
- What is a C++ Friend Class?
- A Function Friendly to Multiple Classes
- C++ Friend Class vs. Friend Function in C++
- Some Important Points About Friend Functions and Classes in C++
- Conclusion
- Frequently Asked Questions
- What Is Function Overriding In C++?
- The Working Mechanism Of Function Overriding In C++
- Real-Life Example Of Function Overriding In C++
- Accessing Overriding Function In C++
- Accessing Overridden Function In C++
- Function Call Binding With Class Objects | Function Overriding In C++
- Function Call Binding With Base Class Pointers | Function Overriding In C++
- Advantages Of Function Overriding In C++
- Variations In Function Overriding In C++
- Function Overloading In C++
- Function Overloading Vs Function Overriding In C++
- Conclusion
- Frequently Asked Questions
- Errors In C++
- What Is Exception Handling In C++?
- Exception Handling In C++ Program Example
- C++ Exception Handling: Basic Keywords
- The Need For C++ Exception Handling
- C++ Standard Exceptions
- C++ Exception Classes
- User-Defined Exceptions In C++
- Advantages & Disadvantages Of C++ Exception Handling
- Conclusion
- Frequently Asked Questions
- What Are Templates In C++ & How Do They Work?
- Types Of Templates In C++
- What Are Function Templates In C++?
- C++ Template Functions With Multiple Parameters
- C++ Template Function Overloading
- What Are Class Templates In C++?
- Defining A Class Member Outside C++ Template Class
- C++ Template Class With Multiple Parameters
- What Is C++ Template Specialization?
- How To Specify Default Arguments For Templates In C++?
- Advantages Of C++ Templates
- Disadvantages Of C++ Templates
- Difference Between Function Overloading And Templates In C++
- Conclusion
- Frequently Asked Questions
- Structure
- Structure Declaration
- Initialization of Structure
- Copying and Comparing Structures
- Array of Structures
- Nested Structures
- Pointer to a Structure
- Structure as Function Argument
- Self Referential Structures
- Class
- Object Declaration
- Accessing Class Members
- Similarities between Structure and Class
- Which One Should You Choose?
- Key Difference Between a Structure and Class
- Summing Up
- Test Your Skills: Quiz Time
- What Is A Class And Object In C++?
- What Is An Object In C++?
- How To Create A Class & Object In C++? With Example
- Interview Spotlight: Classes & Objects In Adobe & Pixar Interviews
- Access Modifiers & Class/ Object In C++
- Member Functions Of A Class In C++
- How To Access Data Members And Member Functions?
- Significance Of Class & Object In C++
- Did You Know? The Concept of Classes & Object Powers Major Apps
- What Are Constructors In C++ & Its Types?
- What Is A Destructor Of Class In C++?
- An Array Of Objects In C++
- Object In C++ As Function Arguments
- The this (->) Pointer & Classes In C++
- The Need For Semicolons At The End Of A Class In C++
- Conclusion
- Frequently Asked Questions
- What Are Static Members In C++?
- Static Member Functions in C++
- Ways To Call Static Member Function In C++
- Properties Of Static Member Function In C++
- Need Of Static Member Functions In C++
- Regular Member Function Vs. Static Member Function In C++
- Limitations Of Static Member Functions In C++
- Conclusion
- Frequently Asked Questions
- What Is Constructor In C++?
- Characteristics Of A Constructor In C++
- Types Of Constructors In C++
- Default Constructor In C++
- Parameterized Constructor In C++
- Copy Constructor In C++
- Dynamic Constructor In C++
- Benefits Of Using Constructor In C++
- How Does Constructor In C++ Differ From Normal Member Function?
- Constructor Overloading In C++
- Constructor For Array Of Objects In C++
- Constructor In C++ With Default Arguments
- Initializer List For Constructor In C++
- Dynamic Initialization Using Constructor In C++
- Conclusion
- Frequently Asked Questions
- What Is A Constructor In C++?
- What Is Constructor Overloading In C++?
- Dеclaration Of Constructor Ovеrloading In C++
- Condition For Constructor Overloading In C++
- How Constructor Ovеrloading In C++ Works?
- Examples Of Constructor Overloading In C++
- Lеgal & Illеgal Constructor Ovеrloading In C++
- Types Of Constructors In C++
- Characteristics Of Constructors In C++
- Advantage Of Constructor Overloading In C++
- Disadvantage Of Constructor Overloading In C++
- Conclusion
- Frеquеntly Askеd Quеstions
- What Is A Destructor In C++?
- Rules For Defining A Destructor In C++
- When Is A Destructor in C++ Called?
- Order Of Destruction In C++
- Default Destructor & User-Defined Destructor In C++
- Virtual Destructor In C++
- Pure Virtual Destructor In C++
- Key Properties Of Destructor In C++ You Must Know
- Explicit Destructor Calls In C++
- Destructor Overloading In C++
- Difference Between Normal Member Function & Destructor In C++
- Important Uses Of Destructor In C++
- Conclusion
- Frequently Asked Questions
- What Is A Constructor In C++?
- What Is A Destructor In C++?
- Difference Between Constructor And Destructor In C++
- Constructor In C++ | A Brief Explanation
- Destructor In C++ | A Brief Explanation
- Difference Between Constructor And Destructor In C++ Explained
- Order Of Calling Constructor And Destructor In C++ Classes
- Conclusion
- Frequently Asked Questions
- Test Your Skills: Quiz Time
- What Is Type Conversion In C++?
- What Is Type Casting In C++?
- Types Of Type Conversion In C++
- Implicit Type Conversion (Coercion) In C++
- Explicit Type Conversion (Casting) In C++
- Advantages Of Type Conversion In C++
- Disadvantages Of Type Conversion In C++
- Difference Between Type Casting & Type Conversion In C++
- Application Of Type Casting In C++
- Conclusion
- Frequently Asked Questions
- What Is A Copy Constructor In C++?
- Characteristics Of Copy Constructors In C++
- Types Of Copy Constructors In C++
- When Do We Call The Copy Constructor In C++?
- When Is A User-Defined Copy Constructor Needed In C++?
- Types Of Constructor Copies In C++
- Can We Make The Copy Constructor In C++ Private?
- Assignment Operator Vs Copy Constructor In C++
- Example Of Class Where A Copy Constructor Is Essential
- Uses Of Copy Constructors In C++
- Conclusion
- Frequently Asked Questions
- Why Do You Need Object-Oriented Programming (OOP) In C++?
- OOPs Concepts In C++ With Examples
- The Class OOPs Concept In C++
- The Object OOPs Concept In C++
- The Inheritance OOPs Concept In C++
- Polymorphism OOPs Concept In C++
- Abstraction OOPs Concept In C++
- Encapsulation OOPs Concept In C++
- Other Features Of OOPs In C++
- Benefits Of OOP In C++ Over Procedural-Oriented Programming
- Disadvantages Of OOPS Concept In C++
- Why Is C++ A Partial OOP Language?
- Conclusion
- Frequently Asked Questions
- Introduction To Abstraction In C++
- Types Of Abstraction In C++
- What Is Data Abstraction In C++?
- Understanding Data Abstraction In C++ Using Real Life Example
- Ways Of Achieving Data Abstraction In C++
- What Is An Abstract Class?
- Advantages Of Data Abstraction In C++
- Use Cases Of Data Abstraction In C++
- Encapsulation Vs. Abstraction In C++
- Conclusion
- Frequently Asked Questions
- What Is Encapsulation In C++?
- How Does Encapsulation Work In C++?
- Types Of Encapsulation In C++
- Why Do We Need Encapsulation In C++?
- Implementation Of Encapsulation In C++
- Access Specifiers & Encapsulation In C++
- Role Of Access Specifiers In Encapsulation In C++
- Member Functions & Encapsulation In C++
- Data Hiding & Encapsulation In C++
- Features Of Encapsulation In C++
- Advantages & Disadvantages Of Encapsulation In C++
- Difference Between Abstraction and Encapsulation In C++
- Conclusion
- Frequently Asked Questions
- What Is Inheritance In C++?
- What Are Child And Parent Classes?
- Syntax And Structure Of Inheritance In C++
- Implementing Inheritance In C++
- Importance Of Inheritance In C++
- Types Of Inheritance In C++
- Visibility Modes Of Inheritance In C++
- Access Modifiers & Inheritance In C++
- How To Make A Private Member Inheritable?
- Member Function Overriding In Inheritance In C++
- The Diamond Problem | Inheritance In C++ & Ambiguity
- Ways To Avoid Ambiguity Inheritance In C++
- Why & When To Use Inheritance In C++?
- Advantages Of Inheritance In C++
- The Disadvantages Of Inheritance In C++
- Conclusion
- Frequently Asked Questions
- What Is Hybrid Inheritance In C++?
- Importance Of Hybrid Inheritance In Object Oriented Programming
- Example Of Hybrid Inheritance In C++: Using Single and Multiple Inheritance
- Example Of Hybrid Inheritance In C++: Using Multilevel and Hierarchical Inheritance
- Real-World Applications Of Hybrid Inheritance In C++
- Conclusion
- Frequently Asked Questions
- What Is Multiple Inheritance In C++?
- Examples Of Multiple Inheritance In C++
- Ambiguity Problem In Multiple Inheritance In C++
- Ambiguity Resolution In Multiple Inheritance In C++
- The Diamond Problem In Multiple Inheritance In C++
- Visibility Modes In Multiple Inheritance In C++
- Advantages & Disadvantages Of Multiple Inheritance In C++
- Multiple Inheritance Vs. Multilevel Inheritance In C++
- Conclusion
- Frequently Asked Questions
- What Is Multilevel Inheritance In C++?
- Block Diagram For Multilevel Inheritance In C++
- Multilevel Inheritance In C++ Example
- Constructor & Multilevel Inheritance In C++
- Use Cases Of Multilevel Inheritance In C++
- Multiple Vs Multilevel Inheritance In C++
- Advantages & Disadvantages Of Multilevel Inheritance In C++
- Conclusion
- Frequently Asked Questions
- What Is Hierarchical Inheritance In C++?
- Example 1: Hierarchical Inheritance In C++
- Example 2: Hierarchical Inheritance In C++
- Impact of Visibility Modes In Hierarchical Inheritance In C++
- Advantages And Disadvantages Of Hierarchical Inheritance In C++
- Use Cases Of Hierarchical Inheritance In C++
- Conclusion
- Frequently Asked Questions
- What Are Access Specifiers In C++?
- Types Of Access Specifiers In C++
- Public Access Specifiers In C++
- Private Access Specifier In C++
- Protected Access Specifier In C++
- The Need For Access Specifiers In C++
- Combined Example For All Access Specifiers In C++
- Best Practices For Using Access Specifiers In C++
- Why Can't Private Members Be Accessed From Outside A Class?
- Conclusion
- Frequently Asked Questions
- What Is The Diamond Problem In C++?
- Example Of The Diamond Problem In C++
- Resolution Of The Diamond Problem In C++
- Virtual Inheritance To Resolve Diamond Problem In C++
- Scope Resolution Operator To Resolve Diamond Problem In C++
- Conclusion
- Frequently Asked Questions
substr() In C++ | Syntax, Use Cases, Tips, & More (+Code Examples)
The substr() function in C++ programming language is one of the string methods used to get a part of the original string. It is a predefined method in the standard library and is used for string slicing and handling other string operations like append(), strcat(), etc. In this blog, we will discuss the syntax, use cases/applications, and more about the substr() function in C++ with the help of examples. So let’s get started!
What Is A Substring In C++ (Substr C++)?
To begin with, a substring refers to a part of the longer string. The substr() function in C++ extracts a portion of a string as a newly constructed string. It’s a member of the std::string class, defined in <string>. It is a powerful tool that helps with string slicing, and it is ideal for extracting substrings for further processing.
The substr in C++ takes two parameters, the starting index and the length of the substring we want from that index, and then it returns a new string object to construct a substring from the original string. Let's take a look at its syntax, components, and return types, followed by an example.
Syntax of substr() Function in C++
string substr(starting_pos, len_substr)
Here:
- The string keyword indicates that the return type of substr() function is a string.
- starting_pos: an unsigned Integer type input parameter. It denotes the position of the first character to be copied from the original string. (Note that the pos parameter is the position parameter, i.e., it refers to the position from which we want the substring to start.)
- len_substr: an unsigned Integer type input parameter denotes the length of the substring.
Return Type
The substr() function in cpp programming returns a newly constructed object of type String, i.e., std::string containing the extracted substring. Case handling:
- If pos equals the string’s length → returns an empty string.
- If pos exceeds the length → throws std::out_of_range.
- If len stretches past the string’s end → grabs characters until the end. No exception.
Example for substr() in C++ | Finding Substring Using Positive and Negative Indices
Let's understand the substr in C++ using the following example:
#include
#include
using namespace std;
int main() {
string originalString = "#Unstoppable"; //original string
string substr1 = originalString.substr(1, 6); //substring starting from index 1 and length 6
string substr2 = originalString.substr(8, -2); //substring starting from index 8 and length -2
cout << "Substring1 starting at position 1 and length 6 is: " << substr1 << endl;
cout << "Substring2 starting at position 8 and length -2 is: " << substr2 << endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8c3RyaW5nLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgppbnQgbWFpbigpIHsKc3RyaW5nIG9yaWdpbmFsU3RyaW5nID0gIiNVbnN0b3BwYWJsZSI7IC8vb3JpZ2luYWwgc3RyaW5nCnN0cmluZyBzdWJzdHIxID0gb3JpZ2luYWxTdHJpbmcuc3Vic3RyKDEsIDYpOyAvL3N1YnN0cmluZyBzdGFydGluZyBmcm9tIGluZGV4IDEgYW5kIGxlbmd0aCA2CnN0cmluZyBzdWJzdHIyID0gb3JpZ2luYWxTdHJpbmcuc3Vic3RyKDgsIC0yKTsgLy9zdWJzdHJpbmcgc3RhcnRpbmcgZnJvbSBpbmRleCA4IGFuZCBsZW5ndGggLTIKCmNvdXQgPDwgIlN1YnN0cmluZzEgc3RhcnRpbmcgYXQgcG9zaXRpb24gMSBhbmQgbGVuZ3RoIDYgaXM6ICIgPDwgc3Vic3RyMSA8PCBlbmRsOwpjb3V0IDw8ICJTdWJzdHJpbmcyIHN0YXJ0aW5nIGF0IHBvc2l0aW9uIDggYW5kIGxlbmd0aCAtMiBpczogIiA8PCBzdWJzdHIyIDw8IGVuZGw7CgpyZXR1cm4gMDsKfQ==
Output:
Substr1 starting at position 1 and length 6 is: Unstop
Substr2 starting at position 8 and length -2 is: able
Explanation:
We begin by including the <iostream> and <string.h> header files.
- In the main() function, we define a string, originalString, and assign the value "#Unstoppable" to it.
- We then use the C++ substr() to get two substrings of the original:
- In the first case, since the starting index is 1, it implies that the substring1 starts from ‘U’ and ends at the 6th index, which is ‘p’, giving a substring of length 6.
- In the second case, since the length is -2, which is a negative number, the substr function will take all the characters till the end of the string. This is because the parameters of substr() function only take unsigned_integer type values.
- Next, we use the cout statements to print the substrings to the console.
- The results match our expectations: sub1 is exactly six characters from index 1, and sub2 contains everything from index 8 onwards.
- Finally, the main() function closes with a return 0 statement.
Check this out: Boosting Career Opportunities For Engineers Through E-School Competitions
Understanding substr() Basics with Examples
Let’s explore some edge-case examples to better understand how substr() works in C++. Consider a string s = “Unstoppable”. Then the indexes of each character in the sequence of characters in the string will be as follows:
string: U n s t o p p a b l e
index: 0 1 2 3 4 5 6 7 8 9 10
Now consider these cases:
- s.substr(s.begin(), 5)
❌ Compilation Error
Explanation: s.begin() returns an iterator, not an integer. substr() requires an unsigned integer (size_t) as the starting position. - s.substr(2, 3)
✅ Result: "sto"
Explanation: the substr() starts at index 2 ('s') and includes 3 characters: 's', 't', 'o'. - s.substr(*s.begin() - s[0], 6)
✅ Result: "Unstop"
Explanation: *s.begin() yields 'U'; subtracting s[0] (also 'U') equals 0. So, this effectively calls substr(0, 6). - s.substr(2, 0)
✅ Result: "" (empty string)
Explanation: starting at index 2 but taking 0 characters returns an empty string.
Use Cases/ Examples of substr() in C++
The substr() function shines in a variety of real-world string operations, from simple extraction to numeric manipulation. Here's a quick overview of the examples and use cases we'll explore in this section:
- Get a Substring Before a Character: Extracts the part of a string that appears before a specified delimiter.
- All Substrings of a Given String: Iterates through and prints every possible non-empty substring of a string—useful for parsing or analysis tasks
- Sum of All Substrings of a String Representing a Number: Treats each substring as a number and prints the total sum, adding a numeric twist to substring operations.
- Minimum Value of All Substrings of a Numeric String: Finds and outputs the smallest numeric value among all substrings.
- Maximum Value of All Substrings of a Numeric String: Finds and outputs the largest numeric value among all substrings.
- Substring After a Given Character: Extracts the part of a string that appears after a specified delimiter.
Each of these tasks leverages substr() in different ways, demonstrating its versatility—from text parsing to numeric processing. We’ll dive into each example shortly!
How to Get a Substring Before a Character Using substr() in C++?
Let’s assume that you have been given a string and a character. Your task is to print the sub-string followed by the given character. The example below shows how this can be done:
Code Example:
// C++ program to demonstrate functioning of substr()
#include
#include
using namespace std;
int main(){
// Take any string
string s = "Hardwork:Success";
// Find position of ':' using find()
int pos = s.find(":");
// Copy substring before pos
// Extract everything before the ":" in the given string
string sub = s.substr(0, pos);
// prints the result
cout << "String is: " << sub;
return 0;
}
Ly8gQysrIHByb2dyYW0gdG8gZGVtb25zdHJhdGUgZnVuY3Rpb25pbmcgb2Ygc3Vic3RyKCkKI2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8c3RyaW5nLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgppbnQgbWFpbigpewovLyBUYWtlIGFueSBzdHJpbmcKc3RyaW5nIHMgPSAiSGFyZHdvcms6U3VjY2VzcyI7CgovLyBGaW5kIHBvc2l0aW9uIG9mICc6JyB1c2luZyBmaW5kKCkKaW50IHBvcyA9IHMuZmluZCgiOiIpOwoKLy8gQ29weSBzdWJzdHJpbmcgYmVmb3JlIHBvcwovLyBFeHRyYWN0IGV2ZXJ5dGhpbmcgYmVmb3JlIHRoZSAiOiIgaW4gdGhlIGdpdmVuIHN0cmluZwpzdHJpbmcgc3ViID0gcy5zdWJzdHIoMCwgcG9zKTsKCi8vIHByaW50cyB0aGUgcmVzdWx0CmNvdXQgPDwgIlN0cmluZyBpczogIiA8PCBzdWI7CgpyZXR1cm4gMDsKfQ==
Output:
String is: Hardwork
Explanation:
In this example, we begin with the string s (value "Hardwork:Success")
- We then use the find() function to get the index position of the character (:) and store it in the pos variable.
- Next, we use the substr() function to extract the substring from index 0 to pos.
- Here, we are extracting the substring before the delimiter (:) character.
- We store this substring in the variable sub and then print it to the console using the cout statement.
Use substr() in C++ to Print all Substrings of a Given String
Let’s learn how to obtain all possible substrings from a given string.

Example Code:
// C++ program to print all possible substrings of a given string
#include <bits/stdc++.h>
using namespace std;
// Function to print all the sub strings
void subString(string s, int length){
// Pick the starting point in outer loop and vary the lengths of
// different strings for a given starting point in the inner loop
for (int i = 0; i < length; i++)
for (int len = 1; len <= length - i; len++)
cout << s.substr(i, len) << endl;
}
// Driver program to test the above function
int main(){
string s = "code";
subString(s, s.length());
return 0;
}
Ly8gQysrIHByb2dyYW0gdG8gcHJpbnQgYWxsIHBvc3NpYmxlIHN1YnN0cmluZ3Mgb2YgYSBnaXZlbiBzdHJpbmcKI2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgovLyBGdW5jdGlvbiB0byBwcmludCBhbGwgdGhlIHN1YiBzdHJpbmdzCnZvaWQgc3ViU3RyaW5nKHN0cmluZyBzLCBpbnQgbGVuZ3RoKXsKLy8gUGljayB0aGUgc3RhcnRpbmcgcG9pbnQgaW4gb3V0ZXIgbG9vcCBhbmQgdmFyeSB0aGUgbGVuZ3RocyBvZgovLyBkaWZmZXJlbnQgc3RyaW5ncyBmb3IgYSBnaXZlbiBzdGFydGluZyBwb2ludCBpbiB0aGUgaW5uZXIgbG9vcApmb3IgKGludCBpID0gMDsgaSA8IGxlbmd0aDsgaSsrKQpmb3IgKGludCBsZW4gPSAxOyBsZW4gPD0gbGVuZ3RoIC0gaTsgbGVuKyspCmNvdXQgPDwgcy5zdWJzdHIoaSwgbGVuKSA8PCBlbmRsOwp9CgovLyBEcml2ZXIgcHJvZ3JhbSB0byB0ZXN0IHRoZSBhYm92ZSBmdW5jdGlvbgppbnQgbWFpbigpewoKc3RyaW5nIHMgPSAiY29kZSI7CnN1YlN0cmluZyhzLCBzLmxlbmd0aCgpKTsKCnJldHVybiAwOwp9
Output:
c
co
cod
code
o
od
ode
d
de
e
Explanation:
In this example, we begin by defining a function, subString, which takes a string and an integer as parameters.
- The function uses a set of nested for loops to iterate through the string.
- Here, the outer loop determines the starting point, and the inner loop determines the length of the substring to be extracted.
- In every iteration, we use the substr() function with the cout statement to extract and display the substring to the console.
- In the main() function, we define a string variable, s, with the value "code".
- Then, we call the subString() function, passing the string s, and the length of the string (using length() function) to is as arguments.
- The possible substrings of string “code" are { c, co, cod, code, o, od, ode, d, de, e}. We vary the starting point in the outer loop and the lengths of the substring in the inner loop.
Print Sum of all Substrings of a String Representing a Number
Suppose we have been provided with an integer represented as a string, and we have been asked to get the sum of all possible substrings of this string. We can do this using the following:
Code Example:
#include <bits/stdc++.h>
using namespace std;
// Method to convert digit in character format to integer digit
int toDigit(char ch){
return (ch - '0');
}
// Function that returns sum of all substring of string num
int sum_Substrings(string num){
int n = num.length();
// allocating memory equal to length of the string
int sumofdigits[n];
// initialize first value with first digit in the string
sumofdigits[0] = toDigit(num[0]);
int result = sumofdigits[0];
// loop over all digits of string
for (int i = 1; i < n; i++) {
int numi = toDigit(num[i]);
// update each sumofdigits with the previous value
sumofdigits[i] = (i + 1) * numi + 10 * sumofdigits[i - 1];
// adding current value to the result
result += sumofdigits[i];
}
return result;
}
// Driver code to test above methods
int main(){
string num = "423";
cout << sum_Substrings(num) << endl;
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgovLyBNZXRob2QgdG8gY29udmVydCBkaWdpdCBpbiBjaGFyYWN0ZXIgZm9ybWF0IHRvIGludGVnZXIgZGlnaXQKaW50IHRvRGlnaXQoY2hhciBjaCl7CnJldHVybiAoY2ggLSAnMCcpOwp9CgovLyBGdW5jdGlvbiB0aGF0IHJldHVybnMgc3VtIG9mIGFsbCBzdWJzdHJpbmcgb2Ygc3RyaW5nIG51bQppbnQgc3VtX1N1YnN0cmluZ3Moc3RyaW5nIG51bSl7CmludCBuID0gbnVtLmxlbmd0aCgpOwovLyBhbGxvY2F0aW5nIG1lbW9yeSBlcXVhbCB0byBsZW5ndGggb2YgdGhlIHN0cmluZwppbnQgc3Vtb2ZkaWdpdHNbbl07Ci8vIGluaXRpYWxpemUgZmlyc3QgdmFsdWUgd2l0aCBmaXJzdCBkaWdpdCBpbiB0aGUgc3RyaW5nCnN1bW9mZGlnaXRzWzBdID0gdG9EaWdpdChudW1bMF0pOwppbnQgcmVzdWx0ID0gc3Vtb2ZkaWdpdHNbMF07Ci8vIGxvb3Agb3ZlciBhbGwgZGlnaXRzIG9mIHN0cmluZwpmb3IgKGludCBpID0gMTsgaSA8IG47IGkrKykgewppbnQgbnVtaSA9IHRvRGlnaXQobnVtW2ldKTsKLy8gdXBkYXRlIGVhY2ggc3Vtb2ZkaWdpdHMgd2l0aCB0aGUgcHJldmlvdXMgdmFsdWUKc3Vtb2ZkaWdpdHNbaV0gPSAoaSArIDEpICogbnVtaSArIDEwICogc3Vtb2ZkaWdpdHNbaSAtIDFdOwovLyBhZGRpbmcgY3VycmVudCB2YWx1ZSB0byB0aGUgcmVzdWx0CnJlc3VsdCArPSBzdW1vZmRpZ2l0c1tpXTsKfQpyZXR1cm4gcmVzdWx0Owp9CgoKLy8gRHJpdmVyIGNvZGUgdG8gdGVzdCBhYm92ZSBtZXRob2RzCmludCBtYWluKCl7CgpzdHJpbmcgbnVtID0gIjQyMyI7CmNvdXQgPDwgc3VtX1N1YnN0cmluZ3MobnVtKSA8PCBlbmRsOwoKcmV0dXJuIDA7Cn0=
Output:
497
Explanation: The number value of all substrings are { 4, 42, 423, 2, 23, 3 }, and the sum of these substrings is 497.
Minimum Value of all Substrings of a String Representing a Number
We have been given an integer represented as a string. Now our task is to get the minimum of all possible substrings of the given string, which is representing a number.
Code Example:
// C++ program to print the minimum of all the
// substrings of a given string representing a number
#include <bits/stdc++.h>
using namespace std;
void subString(string s, int length){
vector v;
// finding all possible substrings
for (int i = 0; i < length; i++){
for (int len = 1; len <= length - i; len++){
string sub_str =(s.substr(i, len));
int x=stoi(sub_str); // converting to integer format
v.push_back(x);//inserting into a vector
}
}
cout<<*min_element(v.begin(),v.end())<<endl;
}
// Driver program to test above function
int main(){
string s = "9328";
subString(s, s.length());
return 0;
Ly8gQysrIHByb2dyYW0gdG8gcHJpbnQgdGhlIG1pbmltdW0gb2YgYWxsIHRoZQovLyBzdWJzdHJpbmdzIG9mIGEgZ2l2ZW4gc3RyaW5nIHJlcHJlc2VudGluZyBhIG51bWJlcgojaW5jbHVkZSA8Yml0cy9zdGRjKysuaD4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCnZvaWQgc3ViU3RyaW5nKHN0cmluZyBzLCBpbnQgbGVuZ3RoKXsKdmVjdG9yPGludD4gdjsKLy8gZmluZGluZyBhbGwgcG9zc2libGUgc3Vic3RyaW5ncwpmb3IgKGludCBpID0gMDsgaSA8IGxlbmd0aDsgaSsrKXsKZm9yIChpbnQgbGVuID0gMTsgbGVuIDw9IGxlbmd0aCAtIGk7IGxlbisrKXsKc3RyaW5nIHN1Yl9zdHIgPShzLnN1YnN0cihpLCBsZW4pKTsKaW50IHg9c3RvaShzdWJfc3RyKTsgLy8gY29udmVydGluZyB0byBpbnRlZ2VyIGZvcm1hdAp2LnB1c2hfYmFjayh4KTsvL2luc2VydGluZyBpbnRvIGEgdmVjdG9yCn0KfQpjb3V0PDwqbWluX2VsZW1lbnQodi5iZWdpbigpLHYuZW5kKCkpPDxlbmRsOwp9CgovLyBEcml2ZXIgcHJvZ3JhbSB0byB0ZXN0IGFib3ZlIGZ1bmN0aW9uCmludCBtYWluKCl7CgpzdHJpbmcgcyA9ICI5MzI4IjsKc3ViU3RyaW5nKHMsIHMubGVuZ3RoKCkpOwoKcmV0dXJuIDA7Cg==
Output
2
Explanation:
All substrings are { 9, 93, 932, 9328, 3, 32, 328, 2, 28, 8 }, and the minimum value substring is 2.
- We define the function subString(), which accepts two parameters: the string s and the length of the string.
- We then create a vector to store the substrings in integer format.
- Next, we use a set of nested for loops to calculate all possible substrings and convert them to integers, subsequently inserting this into a vector.
- We finally find the minimum element, which the function prints to the console using cout.
- In the main() function, we create a string, s, and call the subString() function to get the minimum value.
Maximum Value of all Substrings of a String Representing a Number
We have been given an integer represented as a string. Now our task is to get the maximum of all possible substrings of the given string, which is representing a number.
Example Code:
// C++ program to find maximum of all possible substrings of given string
#include <bits/stdc++.h>
using namespace std;
void subString(string s, int length){
vector v;
// finding all possible substrings
for (int i = 0; i < length; i++){
for (int len = 1; len <= length - i; len++){
string sub_str =(s.substr(i, len));
int x=stoi(sub_str);// converting to integer format
v.push_back(x);//inserting into a vector
}
}
cout<<*max_element(v.begin(),v.end())<<endl;
}
// Driver program to test above function
int main(){
string s = "423";
subString(s, s.length());
return 0;
}
Ly8gQysrIHByb2dyYW0gdG8gZmluZCBtYXhpbXVtIG9mIGFsbCBwb3NzaWJsZSBzdWJzdHJpbmdzIG9mIGdpdmVuIHN0cmluZwojaW5jbHVkZSA8Yml0cy9zdGRjKysuaD4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCnZvaWQgc3ViU3RyaW5nKHN0cmluZyBzLCBpbnQgbGVuZ3RoKXsKdmVjdG9yPGludD4gdjsKLy8gZmluZGluZyBhbGwgcG9zc2libGUgc3Vic3RyaW5ncwpmb3IgKGludCBpID0gMDsgaSA8IGxlbmd0aDsgaSsrKXsKZm9yIChpbnQgbGVuID0gMTsgbGVuIDw9IGxlbmd0aCAtIGk7IGxlbisrKXsKc3RyaW5nIHN1Yl9zdHIgPShzLnN1YnN0cihpLCBsZW4pKTsKaW50IHg9c3RvaShzdWJfc3RyKTsvLyBjb252ZXJ0aW5nIHRvIGludGVnZXIgZm9ybWF0CnYucHVzaF9iYWNrKHgpOy8vaW5zZXJ0aW5nIGludG8gYSB2ZWN0b3IKfQp9CmNvdXQ8PCptYXhfZWxlbWVudCh2LmJlZ2luKCksdi5lbmQoKSk8PGVuZGw7Cn0KCi8vIERyaXZlciBwcm9ncmFtIHRvIHRlc3QgYWJvdmUgZnVuY3Rpb24KaW50IG1haW4oKXsKCnN0cmluZyBzID0gIjQyMyI7CnN1YlN0cmluZyhzLCBzLmxlbmd0aCgpKTsKCnJldHVybiAwOwp9
Output
423
Explanation:
All substrings are { 4, 42, 423, 2, 23, 3 }, and the maximum value substring is 423.
- We define a function subString() that accepts two parameters: the string s and the length of the string.
- Then, we create a vector to store the substrings in integer format.
- Next, we use a set of nested for loops to calculate all possible substrings and convert them to integers, subsequently inserting this into a vector.
- We finally find the maximum element using C++ STL.
Get Substring Before a Specific Character (With substr() and find())
A common requirement is to extract everything that comes after a delimiter within a string—such as getting the file extension, processing key-value pairs, or parsing URLs. You can do this easily by combining .find() and .substr().
Code Example:
#include
#include
using namespace std;
int main() {
string s = "dog:cat";
// Find position of delimiter ':'
size_t pos = s.find(':');
// Extract everything before it
string sub = s.substr(0, pos);
cout << "Substring before ':' is: " << sub << endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8c3RyaW5nPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwppbnQgbWFpbigpIHsKICAgIHN0cmluZyBzID0gImRvZzpjYXQiOwogICAgLy8gRmluZCBwb3NpdGlvbiBvZiBkZWxpbWl0ZXIgJzonCiAgICBzaXplX3QgcG9zID0gcy5maW5kKCc6Jyk7CiAgICAvLyBFeHRyYWN0IGV2ZXJ5dGhpbmcgYmVmb3JlIGl0CiAgICBzdHJpbmcgc3ViID0gcy5zdWJzdHIoMCwgcG9zKTsKICAgIGNvdXQgPDwgIlN1YnN0cmluZyBiZWZvcmUgJzonIGlzOiAiIDw8IHN1YiA8PCBlbmRsOwogICAgcmV0dXJuIDA7Cn0=
Output:
Substring before ':' is: dog
Explanation:
In this example,
- We define a string s with the value “dog:cat”.
- Then, we use the find() function to get the index of a specific character, i.e., s.find(':') returns the index of ':' (here, 3).
- Next, we use the substr() function, i.e., substr(0, pos), which extracts the string from index 0 up to, but does not include index 3.
- We display this to the console using the cout statement, and the main function closes with a return 0 statement.
Points To Remember For Substr In C++
- The index of the first character is always taken as 0 (not 1).
- The starting_pos and substr_len parameters only accept unsigned integer numbers and no other data type.
- If starting_pos equals (=) the original string length, the function returns an empty string.
- If starting_pos is greater than (>) original string length, it throws an ‘out_of_range’ exception, and there are no changes in the string.
- If substr_len is greater than (>) the size of the original string, then the returned sub-string is [starting_pos, size()).
- If substr_len is not passed as a parameter, then the returned sub-string is [starting_pos, size()).
Conclusion
The C++ substr() function, part of the <string> class, is a powerful tool for extracting parts of a string. It takes two unsigned integer parameters: starting position and length. If the length goes beyond the end, it safely returns characters up to the string's end. However, if the starting position exceeds the string length, substr() throws a std::out_of_range exception—so always validate your inputs. In essence, substr() gives you flexible control over string slicing with predictable behavior when used correctly.
Frequently Asked Questions
Q1. What is a substr() in C++?
The substr() is a method of std::string (defined in <string>) that returns a new string. You specify a start index and length, and it slices that part from the original string. The substr function takes two arguments:
- Starting_pos: Indicating the Position of the first character to be copied from the original string.
- Substr_len: Indicates the desired length of the substring from the first position.
Here is the basic syntax of C++ substr() function:
string substr(starting_pos, len_substr)
Q2. How to get a substring of a string in CPP?
To get the substring of a string in CPP, you can use the substr() function. Here is an example:
#include
#include // including string.h library
using namespace std;
int main() {
string originalString = "Substring";
string sub_string = originalString.substr(0,6);
// starting_pos = 0 and length = 6
// Implies it prints from index=0 to index=5 of the original string
cout << sub_string <<endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8c3RyaW5nLmg+IC8vIGluY2x1ZGluZyBzdHJpbmcuaCBsaWJyYXJ5CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgppbnQgbWFpbigpIHsKCnN0cmluZyBvcmlnaW5hbFN0cmluZyA9ICJTdWJzdHJpbmciOwpzdHJpbmcgc3ViX3N0cmluZyA9IG9yaWdpbmFsU3RyaW5nLnN1YnN0cigwLDYpOwovLyBzdGFydGluZ19wb3MgPSAwIGFuZCBsZW5ndGggPSA2Ci8vIEltcGxpZXMgaXQgcHJpbnRzIGZyb20gaW5kZXg9MCB0byBpbmRleD01IG9mIHRoZSBvcmlnaW5hbCBzdHJpbmcKCmNvdXQgPDwgc3ViX3N0cmluZyA8PGVuZGw7CgpyZXR1cm4gMDsKfQ==
Output:
Substr
Q3. Do I need to include <string.h> for substr()?
No. Use the C++ string header:
#include <string>
Not the C header <string.h> (or <cstring>), which does not provide std::string.
Q4. Does substr() support negative values?
No. Both parameters are size_t (unsigned). Negative values lead to undefined behavior or compilation error.
Q5. Does substr() include the first character?
Yes. The substring starts exactly at the given index and includes that character, continuing for the specified len.
Q6. What if start equals or exceeds the string length?
- If start == str.size(): returns an empty string.
- If start > str.size(): throws a std::out_of_range exception
Q7. Can I remove part of a string using substr()?
Yes, you can use the substr() function in combination with erase() function to remove a part of the string. Example:
string s = "how are you?";
string del = s.substr(3, 4); // "are "
s.erase(3, del.length());
cout << s; // prints "how you?"
This trims a specified segment out of the string.
Test Your Skills: Quiz Time
You might also be interested in reading the following:
- Pointers in C++ | A Roadmap To All Types Of Pointers With Examples
- Decoding The Difference Between Structure And Class In C++
- Typedef In C++ | Syntax, Application & How To Use It (With Examples)
- C++ String Concatenation | All Methods Explained (With Examples)
- String Compare In C++ | Learn To Compare Strings With Examples
An economics graduate with a passion for storytelling, I thrive on crafting content that blends creativity with technical insight. At Unstop, I create in-depth, SEO-driven content that simplifies complex tech topics and covers a wide array of subjects, all designed to inform, engage, and inspire our readers. My goal is to empower others to truly #BeUnstoppable through content that resonates. When I’m not writing, you’ll find me immersed in art, food, or lost in a good book—constantly drawing inspiration from the world around me.
Login to continue reading
And access exclusive content, personalized recommendations, and career-boosting opportunities.
Subscribe
to our newsletter
Comments
Add comment