String Manipulation functions in C++

A few months ago I applied for a software development internship. One of the requirements I had to complete was an online programming test successfully, before I could have a face to face interview. Out of the three questions on the test, I could only answer one of them. The two other questions covered string manipulation and algorithms.

Since I study electrical/electronic engineering, I have never gone into depth with learning algorithms nor did I put in the time to learn about String Manipulation. As you would have guessed, I struggled to complete the test and I didn’t hear back from them, but it was a good learning experience to what to expect in an interview programming test.

This is going to cover, what I wished I learnt beforehand, the four very important string manipulation functions in C++. All of these functions will require the header file.

Strlen

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

</pre>
<pre>#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

int main()
{
char string[80];

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

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

return 0;
}
</pre>
<pre>

Strcmp

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.

</pre>
<pre>#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;
}
</pre>
<pre>

Strcpy

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

</pre>
<pre>#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;
}</pre>
<pre>

Strcat

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

</pre>
<pre>#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;
}</pre>
<pre>
Share this post