How do you reverse a string in place in C or C++?

前端 未结 30 2508
长发绾君心
长发绾君心 2020-11-22 00:37

How do you reverse a string in C or C++ without requiring a separate buffer to hold the reversed string?

30条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 01:26

    If you're looking for reversing NULL terminated buffers, most solutions posted here are OK. But, as Tim Farley already pointed out, these algorithms will work only if it's valid to assume that a string is semantically an array of bytes (i.e. single-byte strings), which is a wrong assumption, I think.

    Take for example, the string "año" (year in Spanish).

    The Unicode code points are 0x61, 0xf1, 0x6f.

    Consider some of the most used encodings:

    Latin1 / iso-8859-1 (single byte encoding, 1 character is 1 byte and vice versa):

    Original:

    0x61, 0xf1, 0x6f, 0x00

    Reverse:

    0x6f, 0xf1, 0x61, 0x00

    The result is OK

    UTF-8:

    Original:

    0x61, 0xc3, 0xb1, 0x6f, 0x00

    Reverse:

    0x6f, 0xb1, 0xc3, 0x61, 0x00

    The result is gibberish and an illegal UTF-8 sequence

    UTF-16 Big Endian:

    Original:

    0x00, 0x61, 0x00, 0xf1, 0x00, 0x6f, 0x00, 0x00

    The first byte will be treated as a NUL-terminator. No reversing will take place.

    UTF-16 Little Endian:

    Original:

    0x61, 0x00, 0xf1, 0x00, 0x6f, 0x00, 0x00, 0x00

    The second byte will be treated as a NUL-terminator. The result will be 0x61, 0x00, a string containing the 'a' character.

提交回复
热议问题