Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App

Strings in C++

Last Updated : 19 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, strings are sequences of characters that are used to store words and text. They are also used to store data, such as numbers and other types of information in the form of text. Strings are provided by <string> header file in the form of std::string class.

Creating a String

Before using strings, first we are creating an instance of std::string class as shown:

C++
string str_name; 

where str_name is the name of the string.

Initializing a String

Initializing means assigning some initial value to the string. This can be done by using assignment operator and the text enclosed inside "" double quotes.

C++
string str = "Some Text here"; 

The text inside "" is called string literal and it is the value that is assigned to the string variables. It can be any text that is the sequence of characters from the ASCII charset.

Printing a String

A string can be referred using its name anywhere in the scope once it is declared. For example, the below example prints string using cout:

C++
#include <iostream> using namespace std;  int main() {          // Creating a string     string greeting = "Welcome to GfG!";          // Accessing string     cout << greeting;      return 0; } 

Output
Welcome to GfG!

The individual characters of the strings can also be accessed using their position (or index) like arrays with [] square brackets. The index in C++ starts from 0 and goes till size - 1, so be careful not go outside this limit.

C++
#include <iostream> using namespace std;  int main() {     string str = "Sonu";          // Accessing 3rd character     cout << str[2] << endl;          // Accessing first character     cout << str[0];      return 0; } 

Output
n S

Updating String

The string variable can be updated with new string literal in a similar way it is initialized.

C++
#include <iostream> using namespace std;  int main() {     string str = "Tara";     cout << str << endl;          // Updating string     str = "Singh";     cout << str;      return 0; } 

A single character can also be changed by first accessing the character and then using assignment operator to assign value.

C++
#include <iostream> using namespace std;  int main() {     string str = "Tara";          // Updating second character     str[1] = 'o';     cout << str;      return 0; } 

Other String Operations

The following operations aims to improve your understanding of the strings in C++ and introduce you to some of the most commonly used operations:

  • Find Length of a String
  • Take String as Input
  • Reverse a String
  • String Concatenation
  • Comparing two strings
  • Different ways to copy a string
  • Find Substring
  • Tokenizing a string
  • Comparing two strings

Pass Strings to Functions

The string can be passed to a function in the same was as any other type of variable.

C++
#include <iostream> using namespace std;  // Taking string as argument void print(string s) {     cout << s;     return; }  int main() {     string s = "GeeksforGeeks";          // Passing string     print(s);     return 0; } 

Output
GeeksforGeeks

C Style Strings

C++ is a superset of C language, so it also inherits the way in which we used to create strings in C. In C, strings were nothing, but an array of characters terminated by a NULL character '\0'. They were created as:

C++
char str[] = "Hello"; 

Due to being array, there were limitations on C strings:

  • Fixed Size: Once declared, the size of the C string cannot be changed.
  • Lack of Easy String Operations: No high-level operations like concatenation or substring extraction. Moreover, updating was also complex.

C++ strings resolve these issues by providing a lot of operations that are easy to perform. Internally, these strings are still implemented as dynamic array of characters (or more precisely vectors) Thats why we can access a single character by its index. But the std::string class act as a wrapper and provides lot of built-in functionality for easier and more efficient handling of strings.

C++ String vs C Strings

The main difference between a string and a character array is that strings are immutable, while character arrays are not.

String

Character Array

Strings define objects that can be represented as string streams.The null character terminates a character array of characters.
No Array decay occurs in strings as strings are represented as objects.

The threat of array decay is present in the case of the character array.

A string class provides numerous functions for manipulating strings.Character arrays do not offer inbuilt functions to manipulate strings.
Memory is allocated dynamically.The size of the character array has to be allocated statically. 

Know more about the difference between strings and character arrays in C++

C++ String Functions

C++ provides some inbuilt functions which are used for string manipulation, such as the strcpy() and strcat() functions for copying and concatenating strings. Some of them are:

Function

Description

length()This function returns the length of the string.
swap() This function is used to swap the values of 2 strings.
size() Used to find the size of string
resize()This function is used to resize the length of the string up to the given number of characters.
find()Used to find the string which is passed in parameters
push_back()This function is used to push the passed character at the end of the string
pop_back() This function is used to pop the last character from the string
clear() This function is used to remove all the elements of the string.
strncmp()This function compares at most the first num bytes of both passed strings.
strncpy()This function is similar to strcpy() function, except that at most n bytes of src are copied
strrchr()This function locates the last occurrence of a character in the string.
strcat()This function appends a copy of the source string to the end of the destination string
find()This function is used to search for a certain substring inside a string and returns the position of the first character of the substring. 
replace()This function is used to replace each element in the range [first, last) that is equal to old value with new value.
substr()This function is used to create a substring from a given string. 
compare()This function is used to compare two strings and returns the result in the form of an integer.
erase()This function is used to remove a certain part of a string.

rfind()

This function is used to find the string's last occurrence.

These functions are discussed in this article in more detail - String Function in C++


K

kamleshjoshi18
Improve
Article Tags :
  • C++
Practice Tags :
  • CPP

Similar Reads

    C++ Tutorial | Learn C++ Programming
    C++ is a popular programming language that was developed as an extension of the C programming language to include OOPs programming paradigm. Since then, it has become foundation of many modern technologies like game engines, web browsers, operating systems, financial systems, etc.Features of C++Why
    5 min read
    Setting up C++ Development Environment
    C++ is a general-purpose programming language and is widely used nowadays for competitive programming. It has imperative, object-oriented, and generic programming features. C++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. Before we start programming with C++. We will need an enviro
    8 min read
    Writing First C++ Program - Hello World Example
    The "Hello World" program is the first step towards learning any programming language and is also one of the most straightforward programs you will learn. It is the basic program that demonstrates the working of the coding process. All you have to do is display the message "Hello World" on the outpu
    4 min read
    C++ Variables
    In C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be accessed or changed during program execution.Creating a VariableCreating a variable and giving it a name is called variable definition (sometimes called variable
    4 min read
    C++ Data Types
    Data types specify the type of data that a variable can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared as every data type requires a different amount of memory.C++ supports a wide variety of data typ
    7 min read
    Operators in C++
    C++ operators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language.Example:C++#include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a; return 0; }Outpu
    9 min read
    Basic Input / Output in C++
    In C++, input and output are performed in the form of a sequence of bytes or more commonly known as streams.Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the main memory then this process is called input.Output Stream: If the direction of flow of bytes
    5 min read

    Decision Making in C++

    Decision Making in C (if , if..else, Nested if, if-else-if )
    In C, programs can choose which part of the code to execute based on some condition. This ability is called decision making and the statements used for it are called conditional statements. These statements evaluate one or more conditions and make the decision whether to execute a block of code or n
    7 min read
    C++ if Statement
    The C++ if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not executed based on a certain condition. Let's take a look at an example:C++#include <iostream> using namespace std; int main() { int
    3 min read
    C++ if else Statement
    The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false, it won’t. But what if we want to do something else if the condition is false. Here comes the C++ if else statement. We can use the else statement with if statement to exec
    3 min read
    C++ if else if Ladder
    In C++, the if-else-if ladder helps the user decide from among multiple options. The C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C++ else-if ladder is bypassed. I
    3 min read
    C++ Nested if-else Statement
    Nested if-else statements are those statements in which there is an if statement inside another if else. We use nested if-else statements when we want to implement multilayer conditions (condition inside the condition inside the condition and so on). C++ allows any number of nesting levels.Let's tak
    3 min read
    Switch Statement in C++
    In C++, the switch statement is a flow control statement that is used to execute the different blocks of statements based on the value of the given expression. It is an alternative to the long if-else-if ladder which provides an easy way to execute different parts of code based on the value of the e
    5 min read
    Jump statements in C++
    Jump statements are used to manipulate the flow of the program if some conditions are met. It is used to terminate or continue the loop inside a program or to stop the execution of a function.In C++, there is four jump statement:Table of Contentcontinue Statementbreak Statementreturn Statementgoto S
    4 min read

    C++ Loops

    C++ Loops
    In C++ programming, sometimes there is a need to perform some operation more than once or (say) n number of times. For example, suppose we want to print "Hello World" 5 times. Manually, we have to write cout for the C++ statement 5 times as shown.C++#include <iostream> using namespace std; int
    7 min read
    for Loop in C++
    In C++, for loop is an entry-controlled loop that is used to execute a block of code repeatedly for the given number of times. It is generally preferred over while and do-while loops in case the number of iterations is known beforehand.Let's take a look at an example:C++#include <bits/stdc++.h
    6 min read
    C++ While Loop
    In C++, the while loop is an entry-controlled loop that repeatedly executes a block of code as long as the given condition remains true. Unlike the for loop, while loop is used in situations where we do not know the exact number of iterations of the loop beforehand as the loop execution is terminate
    3 min read
    C++ do while Loop
    In C++, the do-while loop is an exit-controlled loop that repeatedly executes a block of code at least once and continues executing as long as a given condition remains true. Unlike the while loop, the do-while loop guarantees that the loop body will execute at least once, regardless of whether the
    4 min read
    Range-Based for Loop in C++
    In C++, the range-based for loop introduced in C++ 11 is a version of for loop that is able to iterate over a range. This range can be anything that is iteratable, such as arrays, strings and STL containers. It provides a more readable and concise syntax compared to traditional for loops.Let's take
    3 min read
    Functions in C++
    A function is a building block of C++ programs that contains a set of statements which are executed when the functions is called. It can take some input data, performs the given task, and return some result. A function can be called from anywhere in the program and any number of times increasing the
    9 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