close
The Wayback Machine - https://web.archive.org/web/20241127231409/https://www.geeksforgeeks.org/cpp-string-functions/
Open In App

String Functions In C++

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

A string is referred to as an array of characters. In C++, a stream/sequence of characters is stored in a char array. C++ includes the std::string class that is used to represent strings. It is one of the most fundamental datatypes in C++ and it comes with a huge set of inbuilt functions. In this article, will look at the functions of string computations.

What is std::string?

The std::string is a class in C++ since C++98. This class is the standard representation for a text string. It includes some typical string operations like find, replace, concatenate, compare etc. It is present in <string> header file.

Declaration and Initialization of String

std::string company = "GeeksforGeeks!";

Commonly Used String Functions in C++

The std::string class contains functions to provide some common string operations. The below table contains some of the most commonly used functions in C++:

S. No.  

Category

Functions and Operators

Functionality

1.

String Length

length() or size()

It will return the length of the string.

2.

Accessing Characters

Indexing (using array[index])

To access individual characters using array indexing.

at()

Used to access a character at a specified index.

3.

Appending and Concatenating Strings

+ Operator

+ operator is used to concatenate two strings.

append()

The append() function adds one string to the end of another.

4.

String Comparison

== Operator

You can compare strings using the == operator.

compare()

The compare() function returns an integer value indicating the comparison result.

5.

Substrings

substr()

Use the substr() function to extract a substring from a string.

6.

Searching

find()

The find() function returns the position of the first occurrence of a substring.

7.

Modifying Strings

replace()

Use the replace() function to modify a part of the string.

insert()

The insert() function adds a substring at a specified position.

erase()

Use the erase() function to remove a part of the string.

8.

Conversion

c_str()

To obtain a C-style string from a std::string, you can use the c_str() function.

Note: The above functions only works for C++ Style strings (std::string objects) not for C Style strings (array of characters).

1. String Length - length() or size()

We can find the length of the string (number of characters) using either length() or size() function of the std::string class.

Syntax

string_object.size()
or
string_object.length()

Parameters

  • This function does not take any parameter.

Return Value

  • This function returns the number of characters in the string object.

Example

std::string text = "geeksforGeeks";
int length = text.length(); 
//or
int length = text.size();

It will return the length of the string text which is 13.

2. Accessing Characters - at()

Generally, we can access the character of a string using the [] array subscript operator and indexing. But std::string also has a function named at() which can be used to access the characters of the string.

Syntax

string_object.at(index);

Parameters

  • index: It represents the position of the character in the string.

Return Value

  • This function returns the character present at the index.

Example

std::string str = "GEEKSFORGEEKS";
std::cout << str.at(3);

The std::cout will print K on the console as it is the character present at index 3.

3. Concatenating Strings - append() or + Operator

We can concatenate string in C++ using two methods:

1. + Operator

The + operator is overloaded in the std::string class to perform string concatenation.

Syntax

string_object1 + string_object2

Example

std::string firstName = "Geeks";
std::string lastName = "forGeeks";
std::string fullName = firstName + " " + lastName; 

+ operator is used to concatenate two strings. The string fullName will be "GeeksforGeeks".

2. append()

The append() function is another member function to concatenate two strings.

Syntax

string_object1.append(string2)

Parameters

  • string2: This function takes the string to be appended as a parameter. It can be both C or C++ Style string.

Return Value

  • Reference to the final string.
std::string base = "Hey! Geeks";
base.append(" Welcome to GeeksforGeeks!"); // Append a string

The append() function adds one string to the end of another.

4. String Comparison - compare() or == Operator

Just like the concatenation, we can do the string comparison using two methods:

1. == Operator

The equality operator can be used to compare the two strings as it is overloaded for this operation in the std::string class.

Syntax

string_object1 == string_object2

This will return true if both the strings are equal, otherwise returns false.

Example

std::string str1 = "apple";
std::string str2 = "banana";
if (str1 == str2) {
    std::cout << "Strings are equal";
}
else {
    std::cout << "Strings are not equal";
}

Here, "Strings are not equal" will be printed as the == operator will return false.

2. compare()

The compare() function is a member function of std::string class which can be used to compare two strings.

Syntax

str1.compare(str2);

Parameters

  • str2: It is the string to be compared. It can be both C or C++ style string.

Return Value

  • If the strings are equal, return zero.
  • If str1 is greater than str2, return value >0
  • If str2 is greater than str1, return value <0

Example

string str1 = "Geeks";
string str2: = "Geeksfor";
int result = str1.compare(str2);

The result will contain a value less than zero as str2 is greater than str1.

We can also compare the substring of str2 using the compare function():

str1.compare(position, length, str2);

 where,

  • position: position of the first character substring.
  • length: length of the substring.
  • str2:  String object to be compared.

5. Searching -  find()

We can use the find() function of the std::string class to check whether a given character or a substring is present in the string or a part of string.

Syntax of find()

str1.find(var);

Parameters

  • var: It can be a C style string, C++ style string, or a character that is to be searched in the string.

Return Value

  • It returns the pointer to the first occurrence of the character or a substring in the string.

Example

std::string text = "C++ Programming";
int position = text.find("Programming"); // Find the position of a substring

The position variable will contain 4 which is the start of the first occurrence of the string "Programming" in string text.

6. Generate Substring - substr()

We can use the substr() function to generate a part of the string as a new string object. It is a member function of the std::string class.

Syntax of substr() in C

str1.substr(start, end);

Parameters

  • start: Starting position of the substring to be generated.
  • end: Ending of the substring to be generated.

Return Type

  • It returns the newly created string object.

Example

std::string text = "Hello, World!";
std::string sub = text.substr(7, 5); // Extract "World"

In the above example. the sub string will contain the "World".

Modifying Strings

The following function allows us to modify the current string.

1. insert()

The insert() function not only allows us to add a string but also allows us to add it at the specified position. It is also a member function of the std::string class.

Syntax

str1.insert(index, str2);

Parameters

  • str2: string to be inserted.
  • index: position of where to insert the new string

Return Type

  • Reference to the str1.

Example

std::string text = "I have a cat.";
text.insert(9, " black"); // Insert " black" at position 9

2. replace()

The replace() function replaces the part of the string with the given other string. Unlike insert, the characters in the part where the new string is to be inserted are removed.

Syntax

str1.replace(index, size, str2);

Parameters

  • index: Index of where to start replacing the new string.
  • size: length of the part of the string that is to be replaced.
  • str2: new string that is to be inserted.

Return Type

  • Reference to the str1.

Example

std::string text = "I like dogs.";
text.replace(7, 4, "cats"); // Replace "dogs" with "cats"

3. erase()

The erase() function is a member function of std::string class that is used to remove a character or a part of the string.

Syntax

str1.erase(start, end);

Parameters

  • start: Starting position.
  • end: Ending position.

Return Type

  • Reference to the str1.

Example

std::string text = "This is an example.";
text.erase(5, 3); // Erase "is "

Convert std::string to C String - c_str)_

The c_str() function is a member function that is used to convert the C++ style string i.e. std::string objects to C style string i.e. array of characters.

Syntax

str1.c_str()

Parameters

  • This function does not take any parameter.

Return Value

  • Pointer to the equivalent array of characters.

Example

std::string str = "C++";
const char* cstr = str.c_str()

Example of String Functions in C++

The below code demonstrate the use of the above specified string functions:

C++
// C++ Code to demostrate various functions available in
// String class

#include <iostream>
#include <string>

using namespace std;

int main()
{
    // Creating and initializing strings
    string greeting = "Hello, World!";
    cout << greeting << endl;
    string name;

    // Input from the user
    cout << "Enter your name: ";
    cin >> name;
    cout << name << endl;

    // String length
    int length = greeting.length();
    cout << length << endl;

    // Accessing characters
    char firstChar = greeting[0];
    char secondChar = greeting.at(1);
    cout << firstChar << " " << secondChar << endl;

    // Appending and concatenating strings
    string firstName = "Geek";
    string lastName = "Geeks";
    string fullName = firstName + " " + lastName;
    cout << fullName << endl;
    string base = "Hello";
    cout << base << endl;
    base.append(" World!");
    cout << base << endl;

    // String comparison
    string str1 = "apple";
    string str2 = "banana";
    if (str1 == str2) {
        cout << "Strings are equal" << endl;
    }
    else {
        cout << "Strings are not equal" << endl;
    }

    int result = str1.compare(str2);
    if (result == 0) {
        cout << "Strings are equal" << endl;
    }
    else if (result < 0) {
        cout << "str1 comes before str2" << endl;
    }
    else {
        cout << "str1 comes after str2" << endl;
    }

    // Substrings
    string text = "Hello, World!";
    cout << text << endl;
    string sub = text.substr(7, 5);
    cout << sub << endl;

    // Searching
    string searchIn = "C++ Programming";
    size_t position = searchIn.find("Programming");
    if (position != string::npos) {
        cout << "Found at position " << position << endl;
    }
    else {
        cout << "Not found" << endl;
    }

    // Modifying strings
    string modify = "I like dogs.";
    modify.replace(7, 4, "cats");
    cout << modify << endl;
    modify.insert(6, " black");
    cout << modify << endl;
    modify.erase(6, 6);
    cout << modify << endl;

    // Conversion
    string str = "C++";
    const char* cstr = str.c_str();
    cout << cstr << endl;

    return 0;
}


Output

Hello, World!
Enter your name: Geeks
Geeks
13
H e
Geek Geeks
Hello
Hello World!
Strings are not equal
str1 comes before str2
Hello, World!
World
Found at position 4
I like cats.
I like black cats.
I like cats.
C++

Previous Article
Next Article

Similar Reads

Find and print duplicate words in std::vector<string> using STL functions
Consider an array of string and find duplicate words in that array and print that duplicate words if exist.Examples: Input : { "welcome", "to", "geeks", "for", "geeks" } Output : geeks Input : { "reduce", "reuse", "recycle", "reduce", "reuse", "recycle", " recycle" } Output : recycle reduce reuse Input : { "Go", "Green" } Output : No Duplicate word
2 min read
C String Functions
The C string functions are built-in functions that can be used for various operations and manipulations on strings. These string functions can be used to perform tasks such as string copy, concatenation, comparison, length, etc. The <string.h> header file contains these string functions. In this article, we will discuss some of the most commo
8 min read
std::string::length, std::string::capacity, std::string::size in C++ STL
Prerequisite: String in C++ String class is one of the features provided by the Standard template library to us, So it comes up with great functionality associated with it. With these Functionalities, we can perform many tasks easily. Let's see a few of the functionalities string class provides. Header File <string> String Functionalities The
6 min read
Virtual Functions in Derived Classes in C++
A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function. In C++, once a member function is declared as a virtua
2 min read
Virtual Functions and Runtime Polymorphism in C++
A virtual function is a member function that is declared in the base class using the keyword virtual and is re-defined (Overridden) in the derived class. It tells the compiler to perform late binding where the compiler matches the object with the right called function and executes it during the runtime. This technique falls under Runtime Polymorphi
8 min read
Algorithm Library Functions in C++ STL
Non-modifying sequence operations std :: all_of : Test condition on all elements in rangestd :: any_of : Test if any element in range fulfills conditionstd :: none_of : Test if no elements fulfill conditionstd :: for_each : Apply function to rangestd :: find : Find value in rangestd :: find_if : Find element in rangestd :: find_if_not : Find elemen
4 min read
asin() and atan() functions in C/C++ with Example
In C++, asin() and atan() is a predefined function used for mathematical calculations. math.h is the header file required for various mathematical functions. All the functions available in this library take double as an argument and return double as the result. asin() Method asin() function is used to find the arc sine of a number means give a sin
3 min read
Explicitly Defaulted and Deleted Functions in C++ 11
Defaulted Function What is a Defaulted Function? Explicitly defaulted function declaration is a new form of function declaration that is introduced into the C++11 standard which allows you to append the '=default;' specifier to the end of a function declaration to declare that function as an explicitly defaulted function. This makes the compiler ge
5 min read
beta(), betaf() and betal() functions in C++ STL
The beta(), betaf() and betal() are built-in functions in C++ STL that are used to compute the beta functionof two positive real values. The function takes two variables x and y as input and returns the beta function of x and y. Beta function (Also known as Euler integral of first kind) of x and y can be defined as: [Tex]$$B(x, y)=\int_0^1 t^{x-1}
3 min read
__builtin_inf() functions of GCC compiler
These functions do not need to include any header file to use them. So it provides faster usage, as these are Built-in functions of GCC compiler which is most used compiler, even in competitive programming. Note: If the compiler shows warning of overflow, use casting before __builtin_inf() function as (data_type)__builtin_inf() 1. __builtin_inf(voi
4 min read
Methods vs. Functions in C++ with Examples
A method is a procedure or function in OOPs Concepts. Whereas, a function is a group of reusable code which can be used anywhere in the program. This helps the need for writing the same code again and again. It helps programmers in writing modular codes. Methods: A method also works the same as that of function. A method is defined inside a class.
3 min read
C++ Functions - Pass By Reference
Several ways exist in which data (or variables) could be sent as an argument to a function. Two of the common ones are Passing by Value and Passing by Reference. Passing by reference allows a function to modify a variable without creating a copy. We have to declare reference variables. The memory location of the passed variable and parameter is the
5 min read
Passing Pointers to Functions In C++
Prerequisites: Pointers in C++Functions in C++ Passing Pointers to functions means declaring the function parameter as a pointer, at the function calling passing the address of the variable and that address will be stored by a parameter that is declared as a pointer. To change the value of any variable in the function we have to pass the address of
4 min read
C++ - Difference Between Functors and Functions
In C++, we have multiple options to operate over the data like in the case where we can use functions and functors. Although both seem to be similar in a few ways but have multiple differences between them. Let's check the differences between functions and functors in C++. What are functions? Functions are pieces of code that can be called from any
3 min read
C++ Map of Functions
Prerequisites: Functions in C++Map in C++ Maps in C++ are a very useful data structure for storing key-value pairs. A map is the best way to store where we can directly find and access the value using a key with the best time complexity. However, did you know that you can also store functions as values in a C++ map? That's right - it is possible to
5 min read
Using Non-Member Friend Functions With Vector in C++ STL
In C++, Non-member buddy functions may access a class's private members while not being members. The class definition declares them friend. Vector containers, dynamic arrays in C++ Standard Library (STL), may dynamically resize as members are added or deleted. You may need to establish a new class with a vector to utilize non-member friend methods
2 min read
Pass Array to Functions in C++
In C++, a collection of elements stored in contiguous memory locations and having the same data type is called an array. Passing arrays to functions is done to perform various operations on array elements without messing up with the main code. In C++, an array can be passed in a function using a pointer or reference. Understanding the different app
5 min read
Can Static Functions Be Virtual in C++?
In C++, a static member function of a class cannot be virtual. Virtual functions are invoked when you have a pointer or reference to an instance of a class. Static functions aren't tied to the instance of a class but they are tied to the class. C++ doesn't have pointers-to-class, so there is no scenario in which you could invoke a static function v
1 min read
Some interesting facts about static member functions in C++
1) static member functions do not have this pointer. For example following program fails in compilation with error "`this' is unavailable for static member functions " C/C++ Code #include<iostream> class Test { static Test * fun() { return this; // compiler error } }; int main() { getchar(); return 0; } 2) A static member function cannot be v
1 min read
Functions that cannot be overloaded in C++
In C++, following function declarations cannot be overloaded. 1) Function declarations that differ only in the return type. For example, the following program fails in compilation. C/C++ Code #include&lt;iostream&gt; int foo() { return 10; } char foo() { return 'a'; } int main() { char x = foo(); getchar(); return 0; } 2) Member function de
3 min read
Pure Functions
A function is called pure function if it always returns the same result for same argument values and it has no side effects like modifying an argument (or global variable) or outputting something. The only result of calling a pure function is the return value. Examples of pure functions are strlen(), pow(), sqrt() etc. Examples of impure functions
2 min read
Can Virtual Functions be Inlined in C++?
Virtual functions are member functions that are declared in the base class using the keyword virtual and can be overridden by the derived class. They are used to achieve Runtime polymorphism or say late binding or dynamic binding. Inline functions are used to replace the function calling location with the definition of the inline function at compil
2 min read
Macros vs Functions
A macro is a name given to a block of C statements as a pre-processor directive. Being a pre-processor, the block of code is communicated to the compiler before entering into the actual coding (main () function). A macro is defined with the pre-processor directive. Macros are pre-processed which means that all the macros would be processed before y
4 min read
fill() and fill_n() functions in C++ STL
A vector, once declared, has all its values initialized to zero. Following is an example code to demonstrate the same. C/C++ Code // C++ program for displaying the default initialization // of the vector vect[] #include&lt;bits/stdc++.h&gt; using namespace std; int main() { // Creating a vector of size 8 vector&lt;int&gt; vect(8); /
3 min read
Return From Void Functions in C++
Void functions are known as Non-Value Returning functions. They are "void" due to the fact that they are not supposed to return values. True, but not completely. We cannot return values but there is something we can surely return from void functions. Void functions do not have a return type, but they can do return values. Some of the cases are list
2 min read
Forward List in C++ | Set 2 (Manipulating Functions)
Forward List in C++ | Set 1 (Introduction and Important Functions) More functions are discussed in this article Some of the operations other than insertions and deletions that can be used in forward lists are as follows : 1. merge() :- This function is used to merge one forward list with other. If both the lists are sorted then the resultant list r
5 min read
List in C++ - Some Useful Functions
Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, the List has slow traversal, but once a position has been found, insertion and deletion is quick. List Useful Functions: 1. emplace(position, value): This function is used to insert an element at the specified position. 2. emplace_back(value) :- This f
7 min read
isalpha() and isdigit() functions in C with cstring examples.
isalpha(c) is a function in C which can be used to check if the passed character is an alphabet or not. It returns a non-zero value if it's an alphabet else it returns 0. For example, it returns non-zero values for 'a' to 'z' and 'A' to 'Z' and zeroes for other characters.Similarly, isdigit(c) is a function in C which can be used to check if the pa
2 min read
strtok() and strtok_r() functions in C with examples
C provides two functions strtok() and strtok_r() for splitting a string by some delimiter. Splitting a string is a very common task. For example, we have a comma-separated list of items from a file and we want individual items in an array. strtok() Function The strtok() method splits str[] according to given delimiters and returns the next token. I
5 min read
Wide char and library functions in C++
Wide char is similar to char data type, except that wide char take up twice the space and can take on much larger values as a result. char can take 256 values which corresponds to entries in the ASCII table. On the other hand, wide char can take on 65536 values which corresponds to UNICODE values which is a recent international standard which allow
7 min read
Practice Tags :
three90RightbarBannerImg