使用指针向后对数组重新排序
Reorder array backwards with pointers
我正在尝试使用指针向后重新排序 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;
}
相关文章:
- 二叉排序树无法编译
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- C++选择排序算法中的逻辑错误
- 使用C++程序合并排序没有得到正确的输出
- 计算排序向量的向量中唯一值的计数
- 排序算法c++
- 使用2个键的cpp-stl::优先级队列排序不正确
- 将结构向量排序为子组
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 数组将排序排序为降序而不是升序
- 如何按姓氏排序并打印新数组
- 将一个数组的每个元素乘以另一个数组的每个元素,并对新的非常大的数组进行排序
- 合并排序 - 返回新数组,而不是将合并的数组复制到输入数组
- 如何对骰子进行排序并创建每个数组中具有相等骰子的新数组,Yahtzee,C++
- 与排序相关的算法(将每个项目替换为排序排序中的索引)
- 如何将未排序数组的排序索引放入新数组中
- "std::"具有排序/排序、存在测试和头/尾访问的数据结构?
- 创建没有重复项的新排序向量
- 使用快速排序排序不会给出排序的数组
- 读取文本行,对它们进行排序并将它们写入新的文本文件