help me please

Dani AI

Generated

The question can mean two different things: either "reverse the whole string" (mirror the characters end-to-end) or "reverse every pair of characters" (swap adjacent pairs so "abcdef" -> "badcfe"). posted a mirror-reverse example; the variants below show a single-for-loop solution for each common interpretation and note the usual edge cases.

#include <string>
#include <utility> // for std::swap

// swap every adjacent pair: "1234" -> "2143", "123" -> "213"
void swapAdjacentPairs(std::string &s) {
    for (size_t i = 0; i + 1 < s.size(); i += 2)
        std::swap(s[i], s[i + 1]);
}
#include <string>
#include <utility>

// mirror-reverse in-place using one for loop with two indices
void reverseInPlace(std::string &s) {
    if (s.empty()) return;
    for (size_t i = 0, j = s.size() - 1; i < j; ++i, --j)
        std::swap(s[i], s[j]);
}

Notes and pitfalls: both routines are O(n) time and O(1) extra space. For odd-length input the adjacent-pair version leaves the final character in place. Use unsigned index types (size_t) to avoid signed/unsigned warnings and check for empty strings before computing s.size()-1. Reversing raw bytes will break multibyte UTF-8 codepoints; handle Unicode at the codepoint/grapheme level if characters (not bytes) must be preserved. For swapping two specific indices a and b, a single std::swap(s[a], s[b]) is sufficient.

Member Avatar for Member #248612

Don't know if this is exactly what you mean:

include <string>
#include <string>
#include <iostream>

using namespace std;

void reverseStringWithLoop(string & str)
{
    size_t len = str.length();
    for (size_t i = 0; i < len / 2; ++i)
    {
        size_t j = len - i - 1;
        swap(str[i], str[j]);
    }
}

int main()
{
    string str("12"); // works with arbitrary string length
    reverseStringWithLoop(str); // same as std::reverse(str.begin(), str.end());
    cout << str;
    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.