Okay, so I know how to reverse the whole string of a vector,

[code]for_each(newLines.begin(), newLines.end(), [](std::string& s){ reverse(s.begin(), s.end()); });
copy(newLines.begin(), newLines.end(), std::ostream_iterator<std::string> (std::cout, "\n")); [/code]

But is there a way to only reverse the first 10 or so characters of a vector string? i.e.

sdjkfskjd sfdsdf sdjflkjsdjklfsdlkjflksdjfkls jklda sdfioss sloidfjosdf

I only want to reverse the "sdjkfskjd" and not the rest of the string?????

Dani AI

Generated

Good suggestion from — reversing a prefix is the right idea. Important caution: advancing an iterator past s.end() is undefined behaviour, so don’t assume every string has 10 characters. In the sample the first token sdjkfskjd is 9 characters, so decide whether you want a fixed-length prefix or “first word” (up to the first whitespace).

A safe, in-place way to reverse a fixed number of characters without touching the rest:

for (auto& s : newLines) {
    size_t n = (s.size() < 10) ? s.size() : 10;
    for (size_t i = 0; i < n/2; ++i)
        std::swap(s[i], s[n-1-i]);
}

If the intention is to reverse the first token (first word) rather than a fixed count, find the first delimiter and reverse up to that position:

for (auto& s : newLines) {
    auto pos = s.find(' ');
    size_t n = (pos == std::string::npos) ? s.size() : pos;
    for (size_t i = 0; i < n/2; ++i)
        std::swap(s[i], s[n-1-i]);
}

Notes: reversing bytes will corrupt multibyte (UTF-8) characters — use a Unicode-aware approach if needed. If you prefer STL, compute n first and call std::reverse on the prefix. As hinted, show complete includes and a minimal compilable example when testing (e.g., <vector>, <string>, <algorithm>, <utility>), and verify behaviour on empty or short strings.

Recommended Answers

All 3 Replies

Change for_each(newLines.begin(), newLines.end(), [](std::string& s){ reverse(s.begin(), s.end()); }); to for_each(newLines.begin(), newLines.end(), [](std::string& s){ reverse(s.begin(), s.begin() + 10); }); to only do the first 10 characters. I assume newLines is of type std::vector<std::string>.

Yes newLine is the vector string. I will give it a try, thanks.

It's hard to tell exactly what you mean without functioning code. The snippet you gave, isn't complete and it's not formatted at all.

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.