使用指针向后对数组重新排序

Reorder array backwards with pointers

本文关键字:新排序 排序 数组 指针      更新时间:2023-10-16

我正在尝试使用指针向后重新排序 C 字符串。 在我的程序中,我接收字符串,然后在for循环中重新排列它。

例如,如果我输入Thomas,那么它应该使用指针返回samohT

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
    int lengthString;
    char name[256];
    cout << "Please enter text: ";
    cin.getline(name, 256);
    cout << "Your text unscrambled: " << name << endl;
    lengthString = strlen(name);
    cout << "length " << lengthString << endl;
    char* head = name;
    char* tail = name;
    for (int i = 0; i < lengthString; i++)
    {
       //swap here?
    }
    for (int j = lengthString - 1; j > -1; j--)
    {
        //swap here?
    }
    return 0;
}

在这两个循环中,我错过了什么?

在C++中,你可以只使用 std::reverse

例如:

std::string str = "Thomas";
std::reverse(str.begin(), str.end());

您似乎正在编写 C 和 C++ 的混合,但您的作业需要 C 字符串。我会这样写。

char str[] = "Thomas";
size_t head = 0;
size_t tail = strlen(str)-1;
while (head<tail)
{
    char tmp = str[head];
    str[head] = str[tail];
    str[tail] = tmp;
    head++;
    tail--;
}

你可以用更少的变量编写这个算法,但我个人觉得这个版本更容易阅读、理解和验证。

如果您更喜欢使用指针而不是索引,那么它看起来像这样:

char str[] = "Thomas";
char *head = str;
char *tail = str + strlen(str) - 1;
while (head<tail)
{
    char tmp = *head;
    *head = *tail;
    *tail = tmp;
    head++;
    tail--;
}

这两个版本实际上是无法区分的。

for (int i = 0; i < (lengthString / 2); ++i)
{
    char tempChar = name[i];
    name[i] = name[lengthString - i - 1];
    name[lengthString - i - 1] = tempChar;
}

编辑:

char* head = name;
char* tail = name + lengthString - 1;
while (head<tail)
{
    char tempChar = *head;
    *head = *tail;
    *tail = tempChar;
    ++head;
    --tail;
}

如果你想在程序中使用 for 循环,你可以这样做,例如:

char reverse[256] = {0};
int reverseIndex = 0;
for (int i = lengthString - 1; i >= 0; i--)
{
  reverse[reverseIndex++] = name[i];
}
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
int main() {
    std::cout << "Please enter text: ";
    std::string s;
    std::getline(std::cin, s);
    std::cout << "Your text unscrambled: " << s << 'n';
    std::reverse(s.begin(), s.end());
    std::cout << "Your text scrambled: " << s << 'n';
    return 0;
}