string reverse
Certainly! Here is an example of reversing a string in C++ along with explanations for each step:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, World!"; // Define a string variable with the content "Hello, World!"
int length = str.length(); // Get the length of the string
for (int i = 0; i < length / 2; i++) { // Loop through the first half of the string
char temp = str[i]; // Store the character at position i in a temporary variable
str[i] = str[length - i - 1]; // Replace character at position i with its corresponding character from the end of the string
str[length - i - 1] = temp; // Replace character at the end of the string with the character stored in the temporary variable
}
cout << "Reversed string: " << str << endl; // Output the reversed string
return 0;
}
Explanation:
#include <iostream>
and#include <string>
: Include necessary header files for input/output and string manipulation.using namespace std;
: Using the standard namespace to avoid prefixing standard functions and objects.string str = "Hello, World!";
: Define a string variablestr
and initialize it with the content "Hello, World!".int length = str.length();
: Determine the length of the string using thelength()
function of thestring
class.for (int i = 0; i < length / 2; i++) { ... }
: Iterate through the first half of the string.char temp = str[i];
: Store the character at positioni
in a temporary variabletemp
.str[i] = str[length - i - 1];
: Swap the character at positioni
with its corresponding character from the end of the string.str[length - i - 1] = temp;
: Replace the character at the end of the string with the character stored in the temporary variable.cout << "Reversed string: " << str << endl;
: Output the reversed string usingcout
.
This code utilizes a for loop to reverse the string by swapping characters from the beginning with their respective counterparts from the end of the string until reaching the midpoint. Finally, it prints the reversed string.