简体   繁体   中英

How can I shift the letters of a string in C++ 17?

For example, shifting from 'Hi' to 'Jk' by shifting forward in the alphabet by two letters.

So far, I have tried this:

string myString = 'Hello';
string shifted = myString + 2;
cout << shifted << endl;

Which works for chars, but won't do anything for strings. Is there anything else that will work?

Use std::transform .

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

int main()
{
    std::string s("hello");
    std::transform(s.begin(), s.end(), s.begin(),
                   [](unsigned char c) -> unsigned char { return c + 2; });

    // if you don't want to flush stdout, you may use "\n" instead of "\n"
    std::cout << s << std::endl;
}

How this works is it operates using a callback on each character, and transforms the string in-place.

The callback merely adds 2 to the unsigned character:

[](unsigned char c) -> unsigned char { return c + 2; }

The rest is just:

std::transform(s.begin(), s.end(), s.begin(), callback);

Simple, extensible, and easy-to-read.

Use a loop:

std::string myString = "Hello";
std::string shifted;

for (auto const &ch : myString)
    shifted += ch + 2;

std::cout << shifted << '\n';

If you want to shift only letters and have them wrap around if a shifted value would be >'Z' or >'z' :

#include <string>
#include <cctype> // std::islower(), std::isupper()

// ...

for (auto const &ch : myString) {
    if (std::islower(static_cast<char unsigned>(ch)))  // *)
        shifted += 'a' + (ch - 'a' + shift) % ('z' - 'a' + 1);

    if (std::isupper(static_cast<char unsigned>(ch)))
        shifted += 'A' + (ch - 'A' + shift) % ('Z' - 'A' + 1);
}

*) Don't feed those functions negative values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM