How to work with STRING IN C++

Mar 15, 2022

What is a string in C++?

Ever thought about what could be the mystery behind those operations for strings that appear in C++? When you grabbed your hair a few strands came in your fingers over the anomaly that is strings. How many functions do they have? Is it endless? Limitless? If you think that strings have made your coding prep a hell of a nightmare, then look no more as we have got you covered. This article is going to solve every question that you ever had on C++ ‘Strings’

But first things first; what are strings?

Simply put: Strings are objects that represent a sequence of characters.

Syntax-

Coming on to the declaration syntax of C-style Strings. We use it as

 char array_name[ string_size ]="String"

The C-Style Character String–

Let’s first learn to define a pretty simple string, we use

string projectString = "doobydobap.";

cout is used for displaying output -cout << projectString << endl;

it will print the same result as

cout << " doobydobap" << endl;

To use the string data type, the C++ string header <string> must be there at

the top of the program.

#include <string>

using namespace std;

 

The C-style character string –This string is actually a one-dimensional array of characters that is terminated by a null character '\0'.

           Char greeting[5] = {‘S’,’t’,’a’,’r’,’\0’};


Output-


 

Alternative ways of defining a string-

String class- The standard C++ library provides a string class type that supports all the operations and functionality.

Let us see the following example −


On compiling and executing the above code, it produces the following result

 

String vs Character Array

String

Char Array

·       A string is a class that defines objects that can be represented as a stream of characters.

·       A character array is simply an array of characters that can be terminated by a null character.

·       Memory is allocated dynamically in the case of strings. More memory can be allocated at run time on demand. As no memory is preallocated, no memory is wasted.

·       The size of the character array has to be allocated statically, if more memory is required at run time it can’t be allocated. Unused allocated memory is also wasted

·       No array decay occurs, as strings are represented as objects.

·       There is a threat of array decay in the case of the character array. 

·       Strings are slower when compared to implementation than character array.

·       Implementation of character array is faster than std:: string. 

·       String class defines a number of functionalities that allow numerous operations on strings.

·       Character arrays do not offer many inbuilt functions to manipulate strings.

 

Concatenation-

We define strings as a one-dimensional array of characters that terminates with a null character(\0).

To join two strings or more, C++ has inbuilt functionality for this purpose. Combining or joining two or more strings in order to form an output string is called a concatenation of strings.

Example:

String No.1: fishball is
String No.2: married to boyfriend.

String objects in C++ are concatenated using the ‘+’ operator to make the new string.

Code: Concatenation of string objects using the ‘+’ operator.

string firstName = " fishball is ";

string lastName = " married to boyfriend ";

string fullName = firstName + lastName;

cout << fullName;

 

 

C++ String Functions (table format)

Let's check out some functions and understand their functionalities:

Function

Description

Int compare(const string& str)

It is used to compare two string objects.

int length()

It is used to find the length of the string.

void swap(string& str)

It is used to swap the values of two string objects.

string substr(int pos,int n)

It creates a new string object of n characters.

int size()

It returns the length of the string in terms of bytes.

void resize(int n)

It is used to resize the length of the string up to n characters.

string& replace(int pos,int len,string& str)

It replaces a portion of the string that begins at character position pos and spans len

characters.

string& append(const string& str)

It adds new characters at the end of another string object.

char& at(int pos)

It is used to access an individual character at a specified position pos.

int find(string& str,int pos,int n)

It is used to find the string specified in the parameter.

int find_first_of(string& str,int pos,int n)

It is used to find the first occurrence of the specified sequence.

int find_first_not_of(string& str,int pos,int n )

It is used to search the string for the first character that does not match with any of the

characters specified in the string.

int find_last_of(string& str,int pos,int n)

It is used to search the string for the last character of a specified sequence.

int find_last_not_of(string& str,int pos)

It searches for the last character that does not match the specified sequence.

string& insert()

It inserts a new character before the character indicated by the position pos.

int max_size()

It finds the maximum length of the string.

void push_back(char ch)

It adds a new character ch at the end of the string.

void pop_back()

It removes the last character of the string.

string& assign()

It assigns a new value to the string.

int copy(string& str)

It copies the contents of one string into another.

char& back()

It returns the reference of the last character.

Iterator begin()

It returns the reference of the first character.

int capacity()

It returns the allocated space for the string.

const_iterator cbegin()

It points to the first element of the string.

const_iterator cend()

It points to the last element of the string.

void clear()

It removes all the elements from the string.

const_reverse_iterator crbegin()

It points to the last character of the string.

const_char* data()

It copies the characters of the string into an array.

bool empty()

It checks whether the string is empty or not.

string& erase()

It removes the characters as specified.

char& front()

It returns a reference to the first character.

string&  operator+=()

It appends a new character at the end of the string.

string& operator=()

It assigns a new value to the string.

char operator[](pos)

It retrieves a character at a specified position pos.

int rfind()

It searches for the last occurrence of the string.

iterator end()

It references the last character of the string.

reverse_iterator rend()

It points to the first character of the string.

void shrink_to_fit()

It reduces the capacity and makes it equal to the size of the string.

char* c_str()

It returns a pointer to an array that contains a null-terminated sequence of characters.

const_reverse_iterator crend()

It references the first character of the string.

reverse_iterator rbegin()

It references the last character of the string.

Voidreserve(inr len)

It requests a change in capacity.

allocator_type get_allocator();

It returns the allocated object associated with the string.

 

Operations on strings ( with example)

o   Input Functions

Function

Definition

getline()

This function is used to store a stream of characters as entered by the user in the object memory.

push_back()

This function is used to input a character at the end of the string.

pop_back()

Introduced from C++11(for strings), this function is used to delete the last character from the string. 

 

 



o   Capacity Functions

capacity()

This function returns the capacity allocated to the string, which can be equal to or more than the size of the string. Additional space is allocated so that when new characters are added to the string, the operations can be done efficiently.

resize()

This function changes the size of the string, the size can be increased or decreased.

length()

This function finds the length of the string.

shrink_to_fit()

This function decreases the capacity of the string and makes it equal to the minimum capacity of the string. This operation is useful to save additional memory if there are no further additions of characters to be done.

 

 

    

o   Iterator Functions

begin()

This function returns an iterator to the beginning of the string.

end()

This function returns an iterator to the end of the string.

rbegin()

This function returns a reverse iterator pointing at the end of the string.

rend()

This function returns a reverse iterator pointing at the beginning of the string.

 

o   Manipulating Functions

copy(“char array”, len, pos) 

This function copies the substring in the target character array mentioned in its arguments. It takes 3 arguments, target char array, length to be copied, and starting position in the string to start copying.

swap()

This function swaps one string with another.

 

Example-

We can conclude that strings are like naming a far and wide ocean as a lake. On the surface, we just have String class and C-style string but on diving deeper we come across a lot of stuff that is a bunch of functions that manipulate null-terminated strings.

Conclusion

·       String -an object of the std::string class that represents a sequence of characters.

·       There are two types of strings in the C++ programming language:

1.     Strings that are objects of string class (The Standard C++ Library string class)

2.     C-strings (C-style Strings)

·       Character Array- an array of characters that can be terminated by a null character.

·       Concatenation of strings -Combining or joining two or more strings in order to form a result string.

·       Functions in strings- that can be used to perform a number of operations on strings by the user.

·       There are mainly four types of functions:

Ø  Input functions

Ø  Capacity functions

Ø  Iterator functions

Ø  Manipulating functions

Urvashi

REFERENCES:

1.     https://www.geeksforgeeks.org/stdstring-class-in-c/

2.     https://www.tutorialspoint.com/cplusplus/cpp_strings.htm

3.     https://www.cplusplus.com/reference/string/string/

4.     https://www.javatpoint.com/cpp-strings

5.     https://www.programiz.com/cpp-programming/strings

6.     https://www.mygreatlearning.com/blog/strings-in-cpp/

7.     https://en.cppreference.com/w/cpp/string/basic_string

8.     https://www.udacity.com/blog/2020/02/c-strings-explained.html