Operations on Strings in C++
Understanding Operations on Strings
String operations involve various manipulations such as concatenation, reversal, and comparison.
We will explore three different methods to perform operations on strings in C++.
Method 1: Using Standard Library Functions
This method uses built-in string functions for operations.
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
string str1 = "Hello";
string str2 = " World";
str1 += str2;
cout << "Concatenated String: " << str1 << endl;
cout << "Length of String: " << str1.length() << endl;
return 0;
}
Length of String: 11
Method 2: Using Character Array Manipulation
This method manually processes each character for operations.
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
void reverseString(char str[]) {
int length = strlen(str);
for (int i = 0; i < length / 2; i++) {
swap(str[i], str[length - i - 1]);
}
}
int main() {
char str[] = "Hello";
reverseString(str);
cout << "Reversed String: " << str << endl;
return 0;
}
Method 3: Using Pointer Manipulation
This method performs operations using pointers.
#include <iostream>
#include <algorithm>
using namespace std;
int compareStrings(const char *str1, const char *str2) {
while (*str1 && *str2 && *str1 == *str2) {
str1++;
str2++;
}
return *str1 - *str2;
}
int main() {
const char str1[] = "Hello";
const char str2[] = "Hello";
int result = compareStrings(str1, str2);
if (result == 0)
cout << "Strings are equal" << endl;
else
cout << "Strings are not equal" << endl;
return 0;
}