Implement string and set operations on the arrays.
We'll cover the following
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:
#include <iostream>#include <string>using namespace std;int main(){string src = "just a string"; // The string to be copiedint lsrc = src.length(); // Length of the stringstring dst = ""; // Creating an empty stringfor (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.
#include <iostream>#include <string>using namespace std;int main(){string str1 = "just a"; // First stringstring str2 = " string"; // Second stringstring str3 = ""; // Creating an empty string to store the concatenation resultfor (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
#include <iostream>#include <string>using namespace std;int main(){string p[] = {"25","55","888","9","30","45"}; // The 1st string which we want to searchint lp = sizeof(p) / sizeof(p[0]); // Storing lengthstring r = "55"; // String to be searchedint 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
#include <iostream>using namespace std;int main(){string p = "was it a car or a cat i saw"; // The string to be reversedcout << "Original string is: " << p << endl;int lp = p.length(); // Length of string pstring q = " "; // Empty string to store the reverseint i = 1;int found = 0;while (i <= lp) // This loop will terminate when i is greater than lp{q += p[lp - i]; // Reversing the stringi++;}cout << "REVERSED string is: " << q;return 0;}
Get hands-on with 1400+ tech skills courses.