Browse by Domains

Strings in C++ | What are Strings in C++?

Let’s assume there are five people standing in front of you named as:

Arjun, Suraj, Divya, Jason, Emily 

in a horizontal line.

Write the first letters of each name in the order:

ASDJE

This is called a sequence of letters.

Similarly, in C++, we have characters that are a collection set of all the symbols such as

 [A-Z],[a-z],[0-9],[@,#,….].

Definition: Any random sequence of characters defined in C++ library set is called a     String in C++.

C++ provides programmers to use strings to make use of text wherever needed. Strings can be printed on screen, reversed, concatenated (i.e. joined), passed to a function, etc.

Since C code can be run on C++ compiler, we can use C style strings in C++.

In C, style strings are represented as an array of character data type which is terminated (ending) with a null character (\0). Their length is fixed.

In C++ , strings must be declared before they are being used.

Declaration Syntax of C style Strings:

char array_name[ string_size ]="String"	

Alternate declaration ways:

char array_name[ ]={‘S’,’t’,’r’,’i’,’n’,’g’,’\0’}
char array_name[7]={‘S’,’t’,’r’,’i’,’n’,’g’,’\0’}

Note: While declaring the string, if the string length = ‘n’ ,minimum string length must be ‘n+1’.

But, C++  provides an efficient way to declare strings.

C++  defines a way to use string objects for holding strings, i.e, we use string data type (of class string) for creating strings. String objects do not have fixed length .

Therefore, C++ supports two types of String Declaration:

  1. C-style string type
  2. String Class type

Code: C Strings

#include < iostream>
using namespace std;
int main()
{
char str [4] = "sun";
count <<str;
return 0;
}

Output: sun

Code: String Objects

#include <iostream>
using namespace std;
int main()
{
string xyz = "sun"
count <<xyz;
return 0;
}

Output: sun

Note: To use the string object, we should include the string library #include <string>

In C++ , memory is allocated dynamically to strings. Which means there is no pre-allocation of memory, which in turn, ensures there is no wastage of memory.

Concatenation:

In our discussion on Strings, we saw that strings are a sequence of characters stored in the memory storage. Technically, we call strings as a one-dimensional array of characters which terminates with a null character(\0).

If we want to join two strings or more, C++  has an inbuilt functionality to support this join. Combining or joining of two or more strings in order to form a result string is called a concatenation of strings.

Example:

String No.1: India won
String No.2: the series in Australia.

Concatenation of string no.1 and string no.2 is: India won the series in Australia.

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

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

#include <iostream>
using namespace std;
int main()
{
string x= "india";
string y = " won the series in austraila";
string result = x+y ;
count <<' string number 1 : <<x<<endl;
count <<' string number 2 : <<y<<endl;
count <<" concatenation of string number 1 and string number 2" " <<result<<endl;
retrun 0;
}


Output:
String Number 1: India
String Number 2: won the series in Australia.

Concatenation of String Number 1 and String Number 2: India won the series in Australia. To concatenate two C style Strings we can use strcat() function.

Code: Concatenation of C style strings using strcat() function:

#include <iostream>
using namespace std;
int main()
{
char s1 [ 100] = " Moon is the natural";
Char s2 [ 100] = " staellite of the earth";
count <<string1:"<<s1<<endl;
count <<"string 2: " <<s2 <<end;
strcat ( s1,s2);
count <<"After concatenation";
retrun 0;
}

Output:

String 1: Moon is the natural
String 2:  satellite of the Earth.

After concatenation:

String 1: Moon is the natural satellite of the Earth.
String 2:  satellite of the Earth

Interpretation:

When the strcat(s1,s2) function is used the s1 string is concatenated with the s2 string and stored in s1. This means that s1 is updated and s2 remains the same as its previous content.

Numbers and Strings

Mathematically speaking: numbers are 0,1,2,3,-3,-2,-8,100,200,2.4,…

Strings are: “Sachin”, “BASICS101”, “999”,etc.

When numbers are written inside “string to be inserted”, then the number is interpreted by C++ compiler as a string.

+ operator in C++ is used for addition of numbers as well as concatenation of two strings.

So, numbers are added using + , and Strings are concatenated using +.

If we add two numbers the result will be also a number:

Example:

int n1=10;
int n2=69;
int sum = n1+n2;
cout<<sum;

Output: 79

If we add two strings the result will be also a string:

Example:

string s1= “15”;
string s2= “-25”;
string conc=s1+s2;
cout<<conc;

Output: 15-25 …(a string)

Note: If we try to add a number and a string then the compiler will throw an error.

Example:

int a=10;
string b= “20”;
string c= a+b ;
cout<< c;

Output:
Error

String Length

If we want to know the length of a string object, then it is possible to find the length. C++ has two functions for finding the length of a string.

These functions are size() and length() functions.

Both these functions have the same meaning and can be used interchangeably.

Code: Length of a string object using size( ) function:

Output:

String Length= 9

Note: While counting the length of a string spaces are also accounted for and null character is not counted.

So length of “Hello”=5

And length of “ Hello ”=7

For calculating the length of C style strings strlen() function is used.

To use strlen() function include the <cstring> header file.

Length of str1=5

Length of str2=6

Note:

The strlen() function takes the string which is terminated by a null character as an input and returns the length of the string as an output. Spaces are also accounted for while counting of the string length. If the string doesn’t contain the null character then the function doesn’t respond to the string which means the behavior of the function is not defined.

User Input Strings

To provide the program a string i.e. an input by the user, we can use the C++ extraction operator >>  on cin keyword to take the string input from the user via keyboard or any input device.

Example:

string a;
cout<< “Enter the capital of Madhya-Pradesh”;
cin>>a; // gets user input from keyboard;
cout<< “ The capital of Madhya-Pradesh is :”<<a;

Output:

Enter the capital of Madhya-Pradesh

The capital of Madhya-Pradesh is : Bhopal  …(If the input is Bhopal)

Note: 

cin keyword is programmed as when there is space it considers it as a terminating character.

This implies that if we give multi-input words to a string then the string will store and display only one word and omits all the words after the first space.

Example:

string name;
cout<< “Enter your name: ”;
cin>>name;;
cout<< “Your name is: ”<<name;

Output:

Enter your name: Abhinav Mehta

Your name is: Abhinav   

…(If the name entered is Abhinav Mehta then only Abhinav is stored in the variable  ‘a’ and rest is omitted therefore the output is Abhinav and not Abhinav Mehta.)

So, to give multi-line, multi-word input to a string we can use the getline( )  function to read the string.

Its syntax is:

getline ( cin , string)

Example:

string a;
cout<< “What is the full name of U.S.A. ?”;
getline(cin,a);
cout<< “The full name of U.S.A. is: ”<<a;

Outline:

What is the full form of the U.S.A.?

The full form of the U.S.A. is the United States of America.

Types of Strings

We have discussed above the type of Strings. So, summarizing here:

  1. The C style string (or C-String) in header cstring of C++  (ported over from C’s string.h), which represents a string as a char array terminated by a null character ‘\0’ (or 0) (null-terminated char array).
  2. The new C++ string class in header <string>. string is a regular class, with public interface defined in the constructors and public member functions.

Access Strings

Suppose we want to access the individual character inside a string. To do so we can use the letter’s index number . This is called Access Strings.

Since string is a array of characters ending with a null character(\0)

Each character is having its index number for accessing that character.

Example:

str= “Flash 99”;

Then,

str[0]= ‘F’   ,  str[1]= ‘l’  ,  str[2]= ‘a’  ,  str[3]= ‘s’  ,  str[4]= ‘h’  ,  str[5]= ‘ ’  ,
str[6]= ‘9’   ,  str[7]= ‘9’   ,  str[8]= ‘\0’      

Therefore, to access the individual letters inside a string , keep in mind that array indexing always starts from 0  and is incremented by +1 every time we move to the next character.

Index is represented inside [ ] square brackets.

These square brackets are preceded with the array / string name.

EXAMPLE:

string my= “Flash 99”;
cout<<my[4];

Output: h

Using Indexes we can also alter the characters i.e. changing the characters inside a string.

Example:

string abc= “MOUSE”;
abc[0]= ‘H’ // M is altered to H
cout<<abc;

Output: HOUSE 

Storing strings in memory

If the string is declared using the C style string format.

Then the individual characters of string are stored in the individual elements of the array

Example:

char str[10]= “CAT”;

The following diagram shows how the string is stored in the memory.

str:

CAT\0

Array elements after the null character are not the part of the string and they are irrelevant.

A “null string” is a string with the null character as it’s first character. The length of a null string is 0.

Example:

char str[10]= “”;

Memory storage of str:

str 

\0

If the string is declared using a string object then the storage of the string is interpreted in a different manner.

Example:

string name= “Karen”;

String name is a string object which has many data members. The data member of name i.e. p is a pointer to the first character in an  array of characters which are dynamically allocated. The data member of name i.e. length contains the length of the string name. Here, it contains 5. The data member of name i.e. capacity contains the number of valid characters in string name which are stored in the array.

(Pointer means it contains the address of that particular field. For more details please refer to the content on pointers in C++.)

A null string in C++ is a string with string length=0 name= “”

Note:

The strings may be stored in Heap or Stack.

Where the string is stored does not depend on the length of the string.

It depends on the compiler and the Operating System in use.

In fedora and red-hat Linux O.S. the strings are  always stored in the Heap

(In C programming variables were stored in the stack. They are not stored in the heap until and unless we  would use malloc/calloc.)

Omitting Namespace

The statement using namespace std is generally considered bad practice among the programmer community.

The best way to  not use this statement is to specify the namespace to which the identifier belongs by  using the scope operator(::) every time we declare a type.

Few of the C++ programs run even without the standard namespace library. For doing so: using namespace std line can be omitted and replaced with the std keyword, followed by the :: operator for usage of string and cout objects.

It is solely up to you if you want to use the namespace library or not .

Example:

#include<iostream>
#include<string>
int main()
{
std:: string abc= “Voila!”;
std:: cout<<abc;
return 0;
}

Note:

While importing the namespace we import all type definitions int the current scope. This library is extremely huge. It has over many hundreds of predefined identifiers, so a developer might overlook the fact that there is another definition of their required object in the std library. So neglection/overlooking of this might make the programmer specify their own implementation and expect it to be used in later parts of the program. Thus there would exist two definitions for the same type in the current namespace. This is illegal in C++, and even after doing so the  program successfully compiles there is absolutely no way of knowing that which definition is being used where in the program so there is an ambiguity regarding usage of definition.

A perfect solution to this  ambiguity  is to explicitly specify (to the compiler )about which namespace user defined identifier should be used for using the scope operator (::) and thus, ambiguity is diminished.

Yeah we know that typing, std:: every time we define a type is very annoying. It even makes our code look bulkier with lots of type definitions. Typing std:: every time makes it difficult to read the code for the other programmers. So be careful while doing so!

Conclusion:

In the above paragraphs, we have shown an alternative method for accessing (using) an identifier from a namespace. There are still other methods possible for doing such work. In all the valid cases avoid importing entire namespaces into the source code for an error free program!

Adopt a good practice of writing programs. They will surely help you in the long run, even though it may take a lot of time in the beginning.

Start writing error-free, unambiguous and robust codes for better results!

Operations on Strings

There are a bucketful of functions predefined in C++ libraries. We have discussed some frequently used by the programmer community here.

Input Functions:

  1. getline( ) : This function is used to store a stream of characters which is entered by the user in  the object memory.
  2. push_back( ): This function is used to input a character at the end of the string.
  3. pop_back( ):  This function is used to delete the last character from the string.

Capacity Functions:

  1. 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 the new characters are added to the string, the operations can be done efficiently.
  2. resize() :- This function changes the size of string, the size can be increased or decreased.
  3. length():-This function finds the length of the string
  4. 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 we are sure that no further addition of characters have to be made.

Iterator Functions:

  1. begin() :- This function returns an iterator to the beginning of the string.
  2. end() :- This function returns an iterator to the end of the string.
  3. rbegin() :- This function returns a reverse iterator pointing at the end of string.
  4. rend() :- This function returns a reverse iterator pointing at the beginning of the string.

Manipulating Functions:

  1. 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 string to start copying.
  2. swap() :- This function swaps one string with another.

Predefined String Functions

FunctionUse
strlenIt calculates the length of the string.
strcatIt appends a string at the ending of another string.
strncatIt appends first ‘n’ characters of a string at the end of another .
strcpyIt copies a string into another string.
strncpyIt copies the first ‘n’ characters of a string into another.
strcmpIt compares two given strings.
strncmpIt compares the first ‘n’ characters of two strings.
strchrIt finds occurrences of a given character inside a string.
strrchrIt finds the last occurrence of a given character inside a string.
strstrIt finds the first occurrence of a given string inside another string.

These predefined functions are part of the cstring library.

This brings us to end of the blog on Strings in C++. We hope you are now well-equipped with this concept. Wondering where to learn the highly coveted in demand skills for free? Check out the courses on Great Learning Academy

Avatar photo
Great Learning Team
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

Your email address will not be published. Required fields are marked *

Great Learning Free Online Courses
Scroll to Top