Inbuilt String Functions in C++
Inbuilt 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;
}
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 :
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;
}
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;
}