Implement string and set operations on the arrays.

Copy a string

In C++, the individual characters in a string can be accessed but not assigned or modified.

The following program copies a string to another string:

Press + to interact
Press + to interact
#include <iostream>
#include <string>
using namespace std;
int main()
{
string src = "just a string"; // The string to be copied
int lsrc = src.length(); // Length of the string
string dst = ""; // Creating an empty string
for (int i = 0; i < lsrc; i++ )
{
dst += src[i]; // Copying the string
}
cout << src << endl;
cout << dst << endl;
return 0;
}

String concatenation

Concatenation means appending a string to another string. The following program concatenates two strings and stores them to another string.

Press + to interact
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1 = "just a"; // First string
string str2 = " string"; // Second string
string str3 = ""; // Creating an empty string to store the concatenation result
for (int i = 0; i < str1.length(); i++ )
{
str3 += str1[i]; // Appending the characters of str1 to str3
}
for (int j = 0; j < str2.length(); j++)
{
str3 += str2[j]; // Appending the characters of str2 to str3
}
cout << str1 << endl;
cout << str2 << endl;
cout << str3 << endl;
return 0;
}

Search a string in an array of strings

The following program checks whether a string or character is present in a string element.

Sample array

p = {"25","55","888","9","30","45"}

Sample value 1 of to be searched

55

Sample output 1

55 is found at index 1

Sample value 2 of to be searched

50

Sample output 2

50 is NOT FOUND in the array
Press + to interact
#include <iostream>
#include <string>
using namespace std;
int main()
{
string p[] = {"25","55","888","9","30","45"}; // The 1st string which we want to search
int lp = sizeof(p) / sizeof(p[0]); // Storing length
string r = "55"; // String to be searched
int i = 0;
int found = 0;
while (i < lp) // Loop that iterates through the whole array
{
if (r == p[i]) // Checks for the element
{
cout << r << " is found at index " << i;
found = 1;
}
i ++;
}
if (found == 0)
{
cout << r << " is NOT FOUND in the array";
}
return 0;
}

Reverse a string

The following program stores the reverse of a string to another string.

Sample string

"was it a car or a cat I saw"

Sample output

ORIGINAL string is: was it a car or a cat i saw
REVERSED string is: was i tac a ro rac a ti saw
Press + to interact
#include <iostream>
using namespace std;
int main()
{
string p = "was it a car or a cat i saw"; // The string to be reversed
cout << "Original string is: " << p << endl;
int lp = p.length(); // Length of string p
string q = " "; // Empty string to store the reverse
int i = 1;
int found = 0;
while (i <= lp) // This loop will terminate when i is greater than lp
{
q += p[lp - i]; // Reversing the string
i++;
}
cout << "REVERSED string is: " << q;
return 0;
}

Get hands-on with 1400+ tech skills courses.