C++ strings are sequences of characters stored in a char array. Strings are used to store words and text. They are also used to store data, such as numbers and other types of information. Strings in C++ can be defined either using the std::string class or the C-style character arrays.

1. C Style Strings
These strings are stored as the plain old array of characters terminated by a null character ‘\0’. They are the type of strings that C++ inherited from C language.
Syntax:
char str[] = "GeeksforGeeks";
Understanding how to work with strings is fundamental in C++. The C++ Course provides a comprehensive overview of string handling techniques, ensuring you can manipulate strings confidently.
Example:
C++
// C++ Program to demonstrate strings
#include <iostream>
using namespace std;
int main()
{
char s[] = "GeeksforGeeks";
cout << s << endl;
return 0;
}
2. std::string Class
These are the new types of strings that are introduced in C++ as std::string class defined inside <string> header file. This provides many advantages over conventional C-style strings such as dynamic size, member functions, etc.
Syntax:
std::string str("GeeksforGeeks");Example:
C++
// C++ program to create std::string objects
#include <iostream>
using namespace std;
int main()
{
string str("GeeksforGeeks");
cout << str;
return 0;
}
One more way we can make strings that have the same character repeating again and again.
Syntax:
std::string str(number,character);
Example:
C++
#include <iostream>
using namespace std;
int main()
{
string str(5, 'g');
cout << str;
return 0;
}
Output:
ggggg
Ways to Define a String in C++
Strings can be defined in several ways in C++. Strings can be accessed from the standard library using the string class. Character arrays can also be used to define strings. String provides a rich set of features, such as searching and manipulating, which are commonly used methods. Despite being less advanced than the string class, this method is still widely used, as it is more efficient and easier to use. Ways to define a string in C++ are:
- Using String keyword
- Using C-style strings
1. Using string Keyword
It is more convenient to define a string with the string keyword instead of using the array keyword because it is easy to write and understand.
Syntax:
string s = "GeeksforGeeks";
string s("GeeksforGeeks");
Example:
C++
// C++ Program to demonstrate use of string keyword
#include <iostream>
using namespace std;
int main()
{
string s = "GeeksforGeeks";
string str("GeeksforGeeks");
cout << "s = " << s << endl;
cout << "str = " << str << endl;
return 0;
}
Outputs = GeeksforGeeks
str = GeeksforGeeks
2. Using C-style strings
Using C-style string libraries functions such as strcpy(), strcmp(), and strcat() to define strings. This method is more complex and not as widely used as the other two, but it can be useful when dealing with legacy code or when you need performance.
char s[] = {'g', 'f', 'g', '\0'};
char s[4] = {'g', 'f', 'g', '\0'};
char s[4] = "gfg";
char s[] = "gfg";Example:
C++
// C++ Program to demonstrate C-style string declaration
#include <iostream>
using namespace std;
int main()
{
char s1[] = { 'g', 'f', 'g', '\0' };
char s2[4] = { 'g', 'f', 'g', '\0' };
char s3[4] = "gfg";
char s4[] = "gfg";
cout << "s1 = " << s1 << endl;
cout << "s2 = " << s2 << endl;
cout << "s3 = " << s3 << endl;
cout << "s4 = " << s4 << endl;
return 0;
}
Outputs1 = gfg
s2 = gfg
s3 = gfg
s4 = gfg
Another example of C-style string:
C++
#include <iostream>
using namespace std;
int main()
{
string S = "Geeeks for Geeks";
cout << "Your string is= ";
cout << S << endl;
return 0;
}
OutputYour string is= Geeeks for Geeks
How to Take String Input in C++
String input means accepting a string from a user. In C++. We have different types of taking input from the user which depend on the string. The most common way is to take input with cin keyword with the extraction operator (>>) in C++. Methods to take a string as input are:
1. Using Cin
The simplest way to take string input is to use the cin command along with the stream extraction operator (>>).
Syntax:
cin>>s;
Example:
C++
// C++ Program to demonstrate string input using cin
#include <iostream>
using namespace std;
int main() {
string s;
cout<<"Enter String"<<endl;
cin>>s;
cout<<"String is: "<<s<<endl;
return 0;
}
OutputEnter String
String is:
Output:
Enter String
GeeksforGeeks
String is: GeeksforGeeks
2. Using getline
The getline() function in C++ is used to read a string from an input stream. It is declared in the <string> header file.
Syntax:
getline(cin,s);
Example:
C++
// C++ Program to demonstrate use of getline function
#include <iostream>
using namespace std;
int main()
{
string s;
cout << "Enter String" << endl;
getline(cin, s);
cout << "String is: " << s << endl;
return 0;
}
OutputEnter String
String is:
Output:
Enter String
GeeksforGeeks
String is: GeeksforGeeks
3. Using stringstream
The stringstream class in C++ is used to take multiple strings as input at once.
Syntax:
stringstream stringstream_object(string_name);
Example:
C++
// C++ Program to demonstrate use of stringstream object
#include <iostream>
#include <sstream>
#include<string>
using namespace std;
int main()
{
string s = " GeeksforGeeks to the Moon ";
stringstream obj(s);
// string to store words individually
string temp;
// >> operator will read from the stringstream object
while (obj >> temp) {
cout << temp << endl;
}
return 0;
}
OutputGeeksforGeeks
to
the
Moon
How to Pass Strings to Functions?
In the same way that we pass an array to a function, strings in C++ can be passed to functions as character arrays. Here is an example program:
Example:
C++
// C++ Program to print string using function
#include <iostream>
using namespace std;
void print_string(string s)
{
cout << "Passed String is: " << s << endl;
return;
}
int main()
{
string s = "GeeksforGeeks";
print_string(s);
return 0;
}
OutputPassed String is: GeeksforGeeks
Pointers and Strings
Pointers in C++ are symbolic representations of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. By using pointers we can get the first character of the string, which is the starting address of the string. As shown below, the given string can be accessed and printed through the pointers.
Example:
C++
// C++ Program to print string using pointers
#include <iostream>
using namespace std;
int main()
{
string s = "Geeksforgeeks";
// pointer variable declared to store the starting
// address of the string
char* p = &s[0];
// this loop will execute and print the character till
// the character value is null this loop will execute and
// print the characters
while (*p != '\0') {
cout << *p;
p++;
}
cout << endl;
return 0;
}
Difference between String and Character array in C++
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.
|
C++ Strings iterator functions
In C++ inbuilt string iterator functions provide the programmer with an easy way to modify and traverse string elements. These functions are:
| Functions | Description |
|---|
| begin() | This function returns an iterator pointing to the beginning of the string. |
| end() | This function returns an iterator that points to the end of the string. |
| rbegin() | This function returns a reverse iterator pointing to the end of the string. |
| rend() | This function returns a reverse iterator pointing to the beginning of the string. |
| cbegin() | This function returns a const_iterator pointing to the beginning of the string. |
| cend() | This function returns a const_iterator pointing to the end of the string. |
| crbegin() | This function returns a const_reverse_iterator pointing to the end of the string. |
| crend() | This function returns a const_reverse_iterator pointing to the beginning of the string. |
Example:
C++
// C++ Program to demonstrate string iterator functions
#include <iostream>
using namespace std;
int main()
{
// declaring an iterator
string::iterator itr;
// declaring a reverse iterator
string::reverse_iterator rit;
string s = "GeeksforGeeks";
itr = s.begin();
cout << "Pointing to the start of the string: " << *itr<< endl;
itr = s.end() - 1;
cout << "Pointing to the end of the string: " << *itr << endl;
rit = s.rbegin();
cout << "Pointing to the last character of the string: " << *rit << endl;
rit = s.rend() - 1;
cout << "Pointing to the first character of the string: " << *rit << endl;
return 0;
}
OutputPointing to the start of the string: G
Pointing to the end of the string: s
Pointing to the last character of the string: s
Pointing to the first character of the string: G
String Capacity Functions
In C++, string capacity functions are used to manage string size and capacity. Primary functions of capacity include:
| Function | Description |
|---|
| length() | This function is used to return the size of the string |
| capacity() | This function returns the capacity which is allocated to the string by the compiler |
| resize() | This function allows us to increase or decrease the string size |
| shrink_to_fit() | This function decreases the capacity and makes it equal to the minimum. |
Example:
C++
#include <iostream>
using namespace std;
int main()
{
string s = "GeeksforGeeks";
// length function is used to print the length of the string
cout << "The length of the string is " << s.length() << endl;
// capacity function is used to print the capacity of the string
cout << "The capacity of string is " << s.capacity()<< endl;
// the string.resize() function is used to resize the string to 10 characters
s.resize(10);
cout << "The string after using resize function is " << s << endl;
s.resize(20);
cout << "The capacity of string before using shrink_to_fit function is "<< s.capacity() << endl;
// shrink to fit function is used to reduce the capacity of the container
s.shrink_to_fit();
cout << "The capacity of string after using shrink_to_fit function is "<< s.capacity() << endl;
return 0;
}
OutputThe length of the string is 13
The capacity of string is 15
The string after using resize function is GeeksforGe
The capacity of string before using shrink_to_fit function is 30
The capacity of string...
In conclusion, this article explains how strings can be defied in C++ using character arrays and string classes. The string class provides more advanced features, while the character array provides basic features but is efficient and easy to use. In this article, we also discussed the various methods to take input from the user.
To know more about std::string class, refer to the article – std::string class in C++
Similar Reads
C++ Tutorial | Learn C++ Programming
C++ is a middle-level programming language that was developed as an extension of the C programming language. In the early 1980s, Bell Labs was an enhancement of the C language to provide support for OOPs (Object Oriented Programming Systems) and additional features. When you look for the successor o
7 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 is used to demonstrate how the coding process works. All you have to do is display the message "Hello World" on the
3 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. In this article, we will learn about the variables in C++ and how to use them in our programs. Let's take a look at
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 ty
6 min read
Operators in C++
In C++, an operator is a symbol that operates on a value to perform specific mathematical or logical computations on given values. They are the foundation of any programming language. Example: [GFGTABS] C++ #include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a;
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 byte
5 min read
Decision Making in C++
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a s
11 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: [GFGTABS] C++ #include <iostream> using namespace std; 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
4 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 ta
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
6 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 Content continue Statementbreak Statementreturn Statementgot
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. [GFGTABS] C++ #include <iostream> using namesp
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: [GFGTABS] C++ #include <bit
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 set of statements that takes input, does some specific computation, and produces output. The idea is to put some commonly or repeatedly done tasks together to make a function so that instead of writing the same code again and again for different inputs, we can call this function.In s
15+ min read
Pointers and References in C++
In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a
5 min read
C++ Arrays
In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location. For example, if we have to store the marks of 4 or 5 students then we can easily store them by creating 5 different variables but what if we want to store marks of 100 st
15 min read
Strings in C++
C++ strings are sequences of characters stored in a char array. Strings are used to store words and text. They are also used to store data, such as numbers and other types of information. Strings in C++ can be defined either using the std::string class or the C-style character arrays. 1. C Style Str
11 min read
Structures, Unions and Enumerations in C++
In this article, we will discuss structures, unions, and enumerations and their differences. The structure is a user-defined data type that is available in C++.Structures are used to combine different types of data types, just like an array is used to combine the same type of data types.A structure
5 min read
new and delete Operators in C++ For Dynamic Memory
Dynamic memory allocation in C/C++ refers to performing memory allocation manually by a programmer. Dynamically allocated memory is allocated on Heap, and non-static and local variables get memory allocated on Stack (Refer to Memory Layout C Programs for details). What are applications? One use of d
6 min read
C++ Object Oriented Programming (OOPs)
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
10 min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which
9 min read
Encapsulation in C++
Encapsulation in C++ is defined as the wrapping up of data and information in a single unit. In Object Oriented Programming, Encapsulation is defined as binding together the data and the functions that manipulate them. Consider a real-life example of encapsulation, in a company, there are different
5 min read
Abstraction in C++
Data abstraction is one of the most essential and important features of object-oriented programming in C++. Abstraction means displaying only essential information and ignoring the details. Data abstraction refers to providing only essential information about the data to the outside world, ignoring
4 min read
C++ Polymorphism
The word "polymorphism" means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father,
7 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio
15+ min read
Exception Handling in C++
In C++, exceptions are runtime anomalies or abnormal conditions that a program encounters during its execution. The process of handling these exceptions is called exception handling. Using the exception handling mechanism, the control from one part of the program where the exception occurred can be
10 min read
File Handling through C++ Classes
File handling is used to store data permanently in a computer. Using file handling we can store our data in secondary memory (Hard disk).How to achieve the File HandlingFor achieving file handling we need to follow the following steps:- STEP 1-Naming a file STEP 2-Opening a file STEP 3-Writing data
8 min read
Templates in C++ with Examples
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types. Rather than writing and maintaining multip
10 min read
The C++ Standard Template Library (STL)
C++ Standard Template Library (STL)
The C++ Standard Template Library (STL) is a set of template classes and functions that provides the implementation of common data structures and algorithms such as lists, stacks, arrays, sorting, searching, etc. It also provides the iterators and functors which makes it easier to work with algorith
9 min read
Vector in C++ STL
In C++, vector is a dynamic array with the ability to resize itself automatically when an element is inserted or deleted. It is the part Standard Template Library (STL) and provide various useful functions for data manipulation. Let's take a look a simple example to demonstrate the use of vector con
9 min read
List in C++ Standard Template Library (STL)
Lists are sequence containers that allow non-contiguous memory allocation. As compared to the vector, the list has slow traversal, but once a position has been found, insertion and deletion are quick (constant time). Normally, when we say a List, we talk about a doubly linked list. For implementing
6 min read
Queue in C++ Standard Template Library (STL)
Queues are a type of container adaptors that operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front. Queues use an encapsulated object of deque or list (sequential container class) as its underlying container, providing a sp
3 min read
Set in C++ Standard Template Library (STL)
Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific sorted order i.e. either ascending or descending. The std::set class is the part of C++ Standard Template Library (STL) and it is define
7 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the <map> header file. Basic std::map Member F
9 min read
Introduction to Iterators in C++
An iterator is an object (like a pointer) that points to an element inside the container. We can use iterators to move through the contents of the container. They can be visualized as something similar to a pointer pointing to some location and we can access the content at that particular location u
6 min read
Algorithm Library | C++ Magicians STL Algorithm
For all those who aspire to excel in competitive programming, only having a knowledge about containers of STL is of less use till one is not aware what all STL has to offer. STL has an ocean of algorithms, for all < algorithm > library functions : Refer here.Some of the most used algorithms on
7 min read
sort() in C++ STL
In C++, sort() is a built-in function used to sort the given range in desired order. It provides a simple and efficient way to sort the data in C++ but it only works on data structures that provide random access to its elements such as vectors and arrays. Let's take a look at an example: [GFGTABS] C
4 min read
for_each loop in C++
Apart from the generic looping techniques, such as "for, while and do-while", C++ in its language also allows us to use another functionality which solves the same purpose termed "for-each" loops. This loop accepts a function which executes over each of the container elements. This loop is defined i
5 min read
Functors in C++
Please note that the title is Functors (Not Functions)!! Consider a function that takes only one argument. However, while calling this function we have a lot more information that we would like to pass to this function, but we cannot as it accepts only one parameter. What can be done? One obvious an
3 min read
C Preprocessors
Preprocessors are programs that process the source code before compilation. Several steps are involved between writing a program and executing a program in C. Let us have a look at these steps before we actually start learning about Preprocessors. You can see the intermediate steps in the above diag
10 min read