string library functions in C++ with examples

In this page, we will learn string and we also perform some of C-string’s function operation


what is string?

In simple words, a string is a sequence of characters or a sentence. That is, a person’s name, place name or message can be a string, eg, Rahul Sharma, India, Good Morning are examples of string.

C++ offers two types of string,

  • C-string or C style string
  • C++ string

C string

The c string is a character array, form of a single-dimensional array. because C++ is an updated version of C so C++ also support all these libraries. apart from this C++ also has owned its string library.

all the given programs below are examples of C-string library function

initialization of a C-string in C++

char string[ ] = "Rahul";
char string[6] = {'R','a','h','u','l',\0'}; 
char string[6] = "Rahul";
char *string = "Rahul"; // using pointer

where string is an identifier.  if a null character is not initialized, the compiler automatically implements it.

C++ string

In modern C ++, a new string class has been added by ANSI / ISO standard C++ which is called C++ string library. this string implemented by class and objects. there is no need for the data-type. here the class replaces the data-type.

Let’s explain this here,

how C++ string improves the C-string and makes it’s easier. There is a difference given below between The C-string and C++ string.

Here the string is pre-defined as a class form in the C++ library so we always first create its object,

string object; //string constructor with no arguments

where a string is a pre-defined class and object is an identifier. here We only pass the data through the object. such as in the class,

string object("string"); // one arguments

it also supports built-in data-type behaviour,

string object = "string";

when performing string operation, the following syntax will be used,

object.string-function(arguments);

where string-function is a public member of a string class.

apart from this, string class contains many constructors, member functions of the string class, operators, iterators to perform operations. so to understand the implementation of a string, you have to first understand the concept of class, object, constructor and destructor.

✍: In the C-string, we perform operations directly using their pr-defined function no restriction of class and object, while all operations in the C++ string perform through classes and objects. performing the same task in a different way.

Turbo C++ (Borland Compiler, C++98) does not support this string class, and as already mentioned C++ also supports the C-string, so the C-string is mentioned here.

Don’t’ confuse in the above syntax, a string is an identifier in the C string while in C++ string, a string will be a class.

view modern C++ library 

How to read a string in C++?

As we know, the cin statement is used to read user-input, but here, we can not use the cin statement. why?

when you use cin statement to store a string, it does not allow, because cin does not read space. to read the string in C++, we use the get() and getline() function, that is,

For example, if we want to store a name “Rahul sherma” then only “Rahul” will store in the cin statement whereas get() and getline(), both will store the complete name.

The syntax of these statements are given below,

gets(variable);
cin.getline(variable, size);

Here is an example where we store a full-length string in C++.

Both functions are defined within the header file stdio, so in a program, we have to include their header file (stdio.h).

use of string

  • No extra statement has to be written in the program. So that the readability of the program remains.
  • Because the readability of the program remains, so it becomes easy to debug the program.
  • Because the extra code of line decreases, the size of the program also decreases.
  • In a program, we use the string library function of the string, which saves time.

✍: without string, we can perform string related task but it becomes complex.

a lot of string functions have been defined in the string library. Some of these important function names and their tasks are given in the table below,

C string library Function

Function Operation
strlen(str) Returns the length of str, excluding ‘\0’
strcmp(str1, str2) Compare two strings
stricmp(str1, str2) Compare two string without case sensitivity
strncmp(str1, str2, n) Compare n characters of each string
strnicmp(str1, str2, n) Compare n characters of each string without case sensitivity
strcpy(str1, str2) Copies string str2 to str1
strncpy(str1, str2, n) Copies n characters from string str2 into str1.
strcat(str1, str2) Append str2 into str1
strncat(str1, str2, n) Append n characters of one string str2 into second-string str1
strcspn(str1, str2) Returns the number of initial consecutive characters of str1 that are not in str2
strspn(str1, str2) Returns the number of initial consecutive characters of str1 that are in str2
strlwr(str) Converts a lowercase string into uppercase
strupr(str) Converts a lowercase string into uppercase
strchr(str1, c) scan str1 in the forward direction for a Specific character c
strrchr(str1, c) scan str1 in the reverse direction for a Specific character c
strdup(str) Copies a string into a newly created location
strrev(str) Reverse a string in the reverse order except ‘\0’.
strstr(str1, str2) scan the sub-string str2 in the str1.

some of these function are followings,

strlen program in C++

#include<iostream>
#include<string.h>
using namespace std;
 
int main()
  {
     char  *str= "rahul singh";
     int str_len;
 
     //calculating string length by strlen
	str_len = strlen(str);
 
     cout<<"size: "str_len;
 
   return 0;
  }

OUTPUT

size: 11

strcmp program in C++

#include<iostream>
#include<string.h>
using namespace std;

int main()
  {
     char str1[] = "Rahul"; //*str1
     char str2[] = "rahul"; //*str2

      if(strcmp(str1,str2)==0)
           cout<<"string Matched";

      else
	 cout<<"string not matched";
return 0;
 }

OUTPUT

string not matched

stricmp program in C++

#include<iostream>
#include<string.h>
using namespace std;

 int main()
 {
   char str1[] = "Rahul"; //*str1
   char str2[] = "rahul"; //*str2

     if(stricmp(str1,str2)==0) //compare string without case sensitivity
	 cout<<"Matched..";

     else
	 cout<<"Not Matched..";
   return 0;
 }

OUTPUT

Matched..

strncmp program in C++

#include<iostream>
#include<string.h>
using namespace std;

int main()
 {
   char str1[] = "Rahul"; //*str1
   char str2[] = "Rahul singh"; //*str2

     if(strncmp(str1,str2,4)==0) // compare only first 5 characters
	 cout<<"Matched..";

     else
	 cout<<"Not Matched..";
return 0;
 }

OUTPUT

Matched..

strnicmp program in C++

#include<iostream>
#include<string.h>
using namespace std;

int main()
  {
     //different string
     char *str1 = "Rahul"; //str1[]
     char *str2 = "rahul"; //str2[]

     if(strnicmp(str1,str2,4)==0) // compare only first 5 characters
	 cout<<"Matched..";

      else
	 cout<<"Not Matched..";
return 0;
 }

OUTPUT

Matched..

strcpy Program in C++

#include<iostream>
#include<string.h>
using namespace std;

 int main()
  {
     char *str1 = "Rahul";
     char *str2;

    strcpy(str2,str1); //copy str1 to str2

    cout<<"str1: "<<str1<<"\n";
    cout<<"str2: "<<str2;

return 0;
 }

OUTPUT

str1: Rahul
str2: Rahul

strncpy Program in C++

#include<iostream>
#include<string.h>
using namespace std;

 int main()
  {
     char str1[] = "Rahul Singh sherma";
     char *str2;

    strncpy(str2,str1,11); //copy only first 11 characters str1 to str2

    cout<<"str1: "<<str1<<"\n";
    cout<<"str2: "<<str2;

 }

OUTPUT

str1: Rahul Singh sherma
str2: Rahul Singh

strcat Program in C++

#include <string.h>
#include <iostream>
using namespace std;

 int main(void)
  {
    char *str1 = "Rahul";
    char *str2 = " ";
    char *str3 = "Singh";

    //append all str2 and str3 to str1
     strcat(str1, str2);
     strcat(str1, str3);

     cout<<"str1: "<<str1;
  return 0;
  }

OUTPUT

str1: Rahul Singh

strncat program in C++

In the *str3 sherma will be skip

#include<iostream>
#include<string.h>
using namespace std;

int main()
  {
      char *str1 = "Rahul";
      char *str2 = " ";
      char *str3 = "Singh sherma";

  //append 1 character from str2 into str1
       strncat(str1,str2,1);

  //append only first 5 characters from str3 into str1 also
       strncat(str1,str3,5);

     //
     cout<<str1;
return 0;
  }

OUTPUT

str1: Rahul Singh

strspn program in C++

#include<iostream>
#include<string.h>
using namespace std;

 int main()
  {
     char *str1 = "rahul singh";
     char *str2 = "rahul sherma";
     int len;

      len = strspn(str1, str2);

    cout<<"Character where strings different is at position: "<<len;

return 0;
  }

OUTPUT

Character where strings different is at position: 7

strscpn Program in C++

#include<iostream>
#include<string.h>
using namespace std;

int main(void)
  {
     char *str1 = "Rahul";
     char *str2 = "rahul";
     int len;

      len = strcspn(str1, str2);

    cout<<"Character where strings different is at position: "<<len;

  return 0;
  }

OUTPUT

Character where strings different is at position: 1

strlwr program in C++

#include<iostream.h>
#include<string.h>
using namespace std;

int main()
  {
     char  *str= "RAHUL SINGH";
     char *str_lwr;

     //convert string into lower case by strlwr
	str_lwr = strlwr(str);

     cout<<str_lwr;

  return 0;
  }

OUTPUT

rahul singh

strupr program in C++

#include<iostream>
#include<string.h>
using namespace std;

 int main()
  {
     char  *str= "rahul singh";
     char *str_upr;

     //convert string into upper case by strupr
	str_upr = strupr(str);

     cout<<str_upr;
return 0;
  }

OUTPUT

RAHUL SINGH

strchr program in C++

#include<iostream>
#include<string.h>
using namespace std;

 int main()
  {
    char *str1 = "Rahul singh";
    char *str2, c = 'i';

    //scan str1 in the forward direction for a character i
      str2= strchr(str1,c);

      if(str2)
	  cout<<"Character "<<c<<" Found at positition: "<<str2-str1;

     else if(!str2)
	  cout<<"Not Found";
return 0;
  }

OUTPUT

Character i Found at position: 7

strrchr program in C++

#include<iostream>
#include<string.h>
using namespace std;

int main()
  {
    clrscr();
    char *str1 = "Rahul singh";
    char *str2, c = 'i';

      //scan str1 in the reverse direction for a character i
      str2= strrchr(str1,c);

      if(str2)
	  cout<<"Character "<<c<<" Found at postition: "<<str2-str1;

     else if(!str2)
	  cout<<"Not Found";
return 0;
  }

OUTPUT

Character i Found at position: 7

strdup program in C++

#include<iostream>
#include<string.h>
using namespace std;

 int main()
  {
     char  *str= "rahul", *dup_str;

     //copy str into newly created location dup_str
	dup_str = strdup(str);

     cout<<dup_str;

     // freeing the space allocated by strdup
     delete dup_str;
return 0;
  }

OUTPUT

rahul

strrev program in C++

#include<iostream.h>
#include<string.h>
using namaespace std;

int main()
  {
    
     char *str = "rahul singh";

      cout<<"Before reverse: "<<str<<endl;

      //reverse a string by strrev
	strrev(str);

      cout<<"After reverse : "<<str;

  }

OUTPUT

Before reverse: Rahul Singh
After reverse : hginS luhaR

strstr  program in C++

#include<iostream.h>
#include<string.h>
using namespace std;

 int main()
  {
    
    char *str1 = "Rahul singh";
    char *str2 = "sin";

//scan the str1 in the reverse direction for substring str2 by strstr
      str2= strstr(str1,str2);

      if(str2)
	  cout<<"string "<<str2<<" Found at postition: "<<str2-str1;

     else if(!str2)
	  cout<<"Not Found";
  }

OUTPUT

string sin Found at position: 6

Let’s try with a real world example below,

real world example o strcmp in C++

This program is designed in a slightly different way. This program will behave like a log system, in which the user is asked for a password. In this, we have compared both passwords (enter password by a user and true password) to each other from strcmp.

#include<iostream>
#include<stdlib> //getline)(
#include <string.h>
using namespace std;

int main()
{
  start:     // goto statement used

  char psd[10];
  char pwd[10]="password";

  cout<<"Enter Password: ";
  cin.getline(psd,10);

  if(strcmp(psd,pwd)==0)
  {
     cout<<"Matched..\n\n\t";
     system("pause");    // pause display screen with a message

  } else {

    cout<<"Try again..";
    goto start;     // transfer control if condition false
  }
}

OUTPUT

Enter Password: password
Matched..
       press any key to continue.

difference between C-string and C++ string

 

C-string or C++ character array C++ string
C-string is a form of an Array, sequence of char data-type. so it is also called character array. C++ string is a class which is pre-defined in the C++ standard Library added by ANSI.
Declaration of C- string will as follows,
char str[size];
where char is data-type and str is an identifier is called variable.
C++ string will be declared as,
string str; // empty string
where the string is a class, already defined in the C++ Standard  Library and str is an object of string class.
initialization of a C-string will be as follows.
char str[size] = “string”;
while C++ string will be as follows,
string str = “string”;
Like an array, it uses an index value to access a single character. No pre-defined function required.
str[n];
It has a pre-defined function to access a single character from a string.
str.at(n);
because this is the form of an array and array is derived data type. so it is also a derived data type. the string is class and class is a user-defined data-type but its not. although, they behave like built-in data-type. as given above.
standard operators can not apply with the character array.
char str1[ ]+ char str2[];// not possible
char str[] = str2[]; // not possible
operators can apply with the C++ string.
str1+ str2; // possible
str1 = str2; // possible
The character array is stored in the String Constant Pool memory location that is a part of the Heap memory. string, stored in the Heap memory location.

Previous- dynamic memory allocation in C++
Next- storage specifiers in C++


Like it?