String manipulation Functions in c++: 

 

Strlen

This is the easiest function of string manipulation c++ out of the four. What it does is return the length of the string in characters.

#include <iostream>
#include <stdio.h>

using namespace std;

int main()
{
char string[80];

cout << "Enter in a string\n";
gets_s(string);

// Get length of the string
cout << "Length is: " << strlen(string);
cout << "\n";

return 0;
}

 

 

How to find the length of the string in c++ without using Strlen?

 

#include<iostream>
#include<stdio.h>

using namespace std;

void main()
{
 string name = "Sahil";
 int count = 0;

 for (int i = 0;i < name[i] != '\0';i++)
 count++;

 cout << "Length of the string is: " << count << endl;
 system("pause");
}

 

https://www.youtube.com/watch?v=28-IgRBRZ8o&t=6s

Strcmp – Compare Two Strings in C++

Strcmp compares two strings and returns zero if both strings are equal. If string 1 is greater than string 2, it will return a positive value, and if string 1 is less than string 2, it returns a negative value.

#include <iostream>
#include <cstring>
#include <cstdio>
 
using namespace std;
 
int main()
{
 char password_input[80];
 
 cout << "Enter your password: ";
 gets(password_input);
 
 // The password which is correct is "password"
 if(!strcmp(password_input, "password"))
 {
  cout << "Password Accepted\n";
 }
 else
 {
  cout << "Password Denied\n";
 }
 
 return 0;
}

 

Strcpy – How to Use strcpy  in C++

Strcpy copies the contents of one string to another, which destroys the contents of the string being copied to.

#include <iostream>
#include <cstring>
 
using namespace std;
 
int main()
{
 char string[50];
 
 strcpy(string, "Hello");
 cout << string << "\n";
 
 // The previous contents of the string will be destroyed here
 strcpy(string, "There");
 cout << string << "\n";
 
 return 0;
}

 

Strcat

Strcat is also a very simple function. It just appends string to the end of string 1. The example code will further clarify this.

#include <iostream>
#include <cstring>
 
using namespace std;
 
int main()
{
 char string1[50], string2[50];
 
 strcpy(string1, "Hi ");
 strcpy(string2, "There ");
 
 strcat(string1, string2);
 
 cout << string1;
 cout << "\n";
 
 return 0;
}

 

How to make a strcat Function in C++?

#include <iostream>
#include <string>
using namespace std;
void main()
{
 char s1[20] = "Hello", s2[20] = "World";
 int j = 0;
 for (int i = 0; s1[i] != '\0'; i++)
 j++;
 for (int i = 0; s2[i] != '\0'; i++)
 {
   s1[j] = s2[i]; j++;
 }
 s1[j] = '\0';
 cout << "String after Concatenation: " << s1 << endl;
 system("pause");
}

 

 

More on cppbetterexplained:

Share this post