Nothing Special   »   [go: up one dir, main page]

Inbuilt String Functions in C++

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

In-built string functions in C++

1. Length of String :

You need to include cstring header file if you want to use this
function. ( ie. #include<cstring>). Using this function one can
calculate string length including space.

Example :
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[] = "abcdef";
cout<<strlen(str); // output = 6
return 0;
}

2. Compare Two String :

String Compare (strcmp(str1,str2)) function is used for comparing


two string. It will return Zero(0) if both string are equal else it will
return non-zero number. This function work on basis of subtraction.
It will substract both the string.

Example :
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str1[] = "abcdef";
char str2[] = "abcd";
char str3[] = "abc";
char str4[] = "abc";
cout<<strcmp(str3,str4); // output = 0 ie. zero
cout<<strcmp(str1,str2); // output = 101 ie. non-zero
return 0;
}

3. Copy String :

String Copy (strcpy(destination_string,source_string)) is used to


copy once string to other string. This function will also copy null
char from the string.

How This function works : STRCPY simply replace char by char of


string. Here first char of source will replace with destination string’s
first character. This will done until source string’s null char
encountered. So If destination string is greater than source then it
will printed up to null char only.

Example :
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str1[] = "abcdef"; //destination string
char str2[] = "mnop"; //source string
strcpy(str1,str2);
cout<<str1; // output = mnop Here we can see str2 is copied
to str1
return 0;
}

4. String N Copy :

This will copy first N characters from the source string to destination
string. This function will not copy null char like String Copy
function.
Syntax : strncpy(destination_string, source_string, n) Here
n=characters

Example :
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str1[] = "abcdef"; //destination string
char str2[] = "mnop"; //source string
strncpy(str1,str2,3);
cout<<str1; // output = mnodef Here we can see str2 is
copied to str1
return 0;
}

5. Concatenate two Strings :

This function simply joins two string into one string.

Here you need to mention size of both string which you want to join.

Example :
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char destination[50] = "Follow"; //destination string
char source[50] = " This Blog"; //source string
strcat(destination,source);
cout<<destination; // output = Follow This Blog
return 0;
}

You might also like