The Wayback Machine - https://web.archive.org/web/20241125172725/https://www.geeksforgeeks.org/strings-in-cpp/
Open In App

Strings in C++

Last Updated : 11 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Strings in C++

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;
}

Output
GeeksforGeeks

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;
}

Output
GeeksforGeeks

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;
}

Output
s = 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;
}

Output
s1 = 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;
}

Output
Your 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:

  • cin
  • getline
  • stringstream

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;
}

Output
Enter 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;
}

Output
Enter 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;
}

Output
GeeksforGeeks
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;
}

Output
Passed 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;
}

Output
Geeksforgeeks

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.

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:

FunctionsDescription
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.
rfind()This function is used to find the string’s last occurrence.
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;
}

Output
Pointing 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:

FunctionDescription
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;
}

Output
The 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++



Previous Article
Next Article

Similar Reads

Minimum Cost to make two Numeric Strings Identical
Given two numeric strings, A and B. A numeric string is a string that contains only digits ['0'-'9'].The task is to make both the strings equal in minimum cost. The only operation that you are allowed to do is to delete a character (i.e. digit) from any of the strings (A or B). The cost of deleting a digit D is D units. Examples: Input : A = "7135"
7 min read
Pairs of strings which on concatenating contains each character of "string"
Given an array of strings arr[]. The task is to find the count of unordered pairs of strings (arr[i], arr[j]), which in concatenation includes each character of the string "string" at least once. Examples: Input: arr[] = { "s", "ng", "stri"} Output: 1 (arr[1], arr[2]) is the only pair which on concatenation will contain every character of the strin
9 min read
C++ program to compare two Strings using Operator Overloading
Pre-requisite: Operator Overloading in C++Given two strings, how to check if the two strings are equal or not, using Operator Overloading. Examples: Input: ABCD, XYZ Output: ABCD is not equal to XYZ ABCD is greater than XYZ Input: Geeks, Geeks Output: Geeks is equal to Geeks Approach: Using binary operator overloading. Declare a class with a string
3 min read
Strings in C++ and How to Create them?
Strings in C++ are used to store text or sequences of characters. In C++ strings can be stored in one of the two following ways: C-style string (using characters)String class Each of the above methods is discussed below: 1. C style string: In C, strings are defined as an array of characters. The difference between a character array and a string is
2 min read
Concatenate the strings in an order which maximises the occurrence of subsequence "ab"
Given N strings containing of characters 'a' and 'b'. These string can be concatenated in any order to make a single final string S. The score of the final string S is defined as the number of occurrences of the subsequence "ab" in it. Now, the task is to concatenate the string in such a way that the score of the final string is maximized. Print th
12 min read
Arrays and Strings in C++
Arrays An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used to store similar types of elements as in the data type must be the same for all elements. They can be used to store the collection of primitive data types such as int, float, doubl
5 min read
Find all strings in lexicographic order possible by replacing digits with 'x', 'y' or 'z'
Given a string str, consisting of lower case English alphabets and digits(0-9), the task is to print all possible strings in lexicographic order that can be formed by replacing each occurrence of a digit with either 'x', 'y' or 'z'. Example: Input: str = "a1b2"Output: axbx axby axbz aybx ayby aybz azbx azby azbzExplanation: These string are the 9 p
6 min read
Generate all the binary strings of N bits
Given a positive integer number N. The task is to generate all the binary strings of N bits. These binary strings should be in ascending order.Examples: Input: 2Output:0 00 11 01 1Input: 3Output:0 0 00 0 10 1 00 1 11 0 01 0 11 1 01 1 1Recommended: Please try your approach on {IDE} first, before moving on to the solution.Approach: The idea is to try
8 min read
Karatsuba Algorithm for fast Multiplication of Large Decimal Numbers represented as Strings
Given two numeric strings A and B, the task is to find the product of the two numeric strings efficiently. Example: Input: A = 5678, B = 1234Output: 7006652 Input: A = 74638463789, B = 35284567382Output: 2633585904851937530398 Approach: The given problem can be solved using Karastuba's Algorithm for Fast Multiplication, the idea is to append zeroes
15+ min read
How to write long strings in Multi-lines C/C++?
Image a situation where we want to use or print a long long string in C or C++, how to do this? In C/C++, we can break a string at any point in the middle using two double quotes in the middle. Below is a simple example to demonstrate the same. C/C++ Code #include<stdio.h> int main() { // We can put two double quotes anywhere in a string char
2 min read
Difference between concatenation of strings using (str += s) and (str = str + s)
A string is a collection of characters. For example, "GeeksforGeeks" is a string. C++ provides primitive data types to create a string. The string can also be initialized at the time of declaration. Syntax: string str; string str = "GeeksforGeeks" Here, "GeeksforGeeks" is a string literal. This article shows the difference between the concatenation
15+ min read
<strings> library in C++ STL
Member functions String.constructor : Construct string object (public member function ).String.destructor : String destructor (public member function )String.operator= : String assignment (public member function ) Iterators Begin : Return iterator to beginning (public member function )End : Return iterator to end (public member function )Advance :
3 min read
Array of Strings in C++ - 5 Different Ways to Create
In C++, a string is usually just an array of (or a reference/points to) characters that ends with the NULL character '\0'. A string is a 1-dimensional array of characters, and an array of strings is a 2-dimensional array of characters where each row contains some string. In this article, we will discuss 5 different ways to create an array of string
6 min read
Vector of Strings in C++
In C++, a vector of strings is a std::vector container that stores multiple strings. It is useful when you need to store a collection of string data in a single container and refer to them quickly. In this article, we will learn about the vector of strings and how to create and use it in C++. Table of Content Vector of Strings in C++Vector of Strin
3 min read
C++ Programming Language
C++ is a programming language that is the foundation of many modern technologies like game engines, web browsers, operating systems financial systems, etc. Bjarne Stroustrup developed it as an extension of the C language. C++ is generally used to create high-performance applications and provides better control of memory and system resources. The la
9 min read
30 OOPs Interview Questions and Answers (2024) Updated
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is <string>. The substring function takes two values pos and len as an argument
8 min read
Virtual Function in C++
A virtual function (also known as virtual methods) is a member function that is declared within a base class and is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the meth
6 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 information about how it affects different properties of the
15+ 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, a husband, and an employee. So the same person ex
7 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 holds its own data members and member functions, w
10 min read
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 set of statements or not. These decision-making sta
11 min read
Priority Queue in C++ Standard Template Library (STL)
A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}). In C++ STL, the top elemen
11 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 container: [GFGTABS] C++ #include <bits/stdc++.h
9 min read
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 that no other part of the code can access this data
10 min read
Operator Overloading in C++
in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning. In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot overload in C++. C++ Operator OverloadingC++ has
9 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 multiple codes, we can write one sort() and pass the dat
10 min read
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the
6 min read
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time an object of a class is created. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor
7 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. The | (bitwise OR) in C takes two nu
7 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg