String Functions in C++

Written by

Vaaruni Agarwal

We learned about arrays and string in C++ now, we are going to divulge deep into the Strings as they constitute an important part in the C++ programming language. In this chapter, we will learn about the string functions.

What are String Functions?

As the name suggests, the string functions are actually the functions that manipulate the strings. These are a special type of functions that are already defined in the C++ header files and can be used by any programmer to manipulate the strings or the character arrays in C++. 

To use the string functions in C++, we must include the header file string.h, which contains the definition of all the string functions.

String Functions in C++:

Following string functions are offered in C++:

Copy Function:

strcpy(s1, s2);

Used to copy the value of s2 into s1. But it works only if s1 has a size big enough to accommodate the s2.

 

Concatenate Function:

strcat(s1, s2);

Concatenates string s2 onto the end of string s1. But it works only if s1 has a size big enough to accommodate the contents of s2.

 

-Length Function:

strlen(str);

Returns the length of the string specified in the parenthesis. Its return type is an integer.

 

Comparison Function:

strcmp(s1, s2);

Compares strings s1 and s2 with each other. This comparison is done in a case sensitive manner, thus, C++ and c++ are two different words here. Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

 

Case Insensitive Comparison Function:

strcmpi(s1, s2);

Compares strings s1 and s2 with each other. This comparison is done in a case insensitive manner, thus, C++ and c++ are the same words here. Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

Below code illustrates the use of some of these string functions:

#include <iostream.h>

#include <string.h>

int main () {

   char str1[10] = "Hello";

   char str2[10] = "World";

   char str3[10];

   int  len ;

   // copy str1 into str3

   strcpy( str3, str1);

   cout << "strcpy( str3, str1) : " << str3 << endl;

   // concatenates str1 and str2

   strcat( str1, str2);

   cout << "strcat( str1, str2): " << str1 << endl;

   // total length of str1 after concatenation

   len = strlen(str1);

   cout << "strlen(str1) : " << len << endl;

}

Output:

strcpy( str3, str1) : Hello

strcat( str1, str2): HelloWorld

strlen(str1) : 10

 

String Functions in C++