C++ 反向数组 [英] C++ Reverse Array

查看:41
本文介绍了C++ 反向数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++ 中,我需要:

In C++, I need to:

  • 从用户输入中读取字符串并将其放入字符数组 [完成]
  • 然后将该数组传递给函数 [done]
  • 该函数应该颠倒字符的顺序[问题!]
  • 然后,回到 main(),它显示带有新反转字符的原始数组.
  • Read in a string from user input and place it into a char array [done]
  • Then pass that array to a function [done]
  • The function is supposed to reverse the order of characters [problem!]
  • Then, back in the main(), it displays that original array with the newly reversed characters.

我在创建实际执行反向操作的函数时遇到问题,因为我有一些限制:

I'm having trouble creating the function that actually does the reversing because I have some restrictions:

  • 我不能有任何本地数组变量.
  • 也没有指针

我的函数只传入原始数组,即:

My function is only passing in the original array ie:

void reverse(char word[])

这是我目前的代码库:

void reverse(char word[]);

void main() 
{
  char word[MAX_SIZE];

  cout << endl << "Enter a word : ";
  cin >> word; 
  cout << "You entered the word " << word << endl;

  reverse(word); 

  cout << "The word in reverse order is " << word << endl;
}

void reverse(char myword[]) 
{
  int i, temp;
  j--;

  for(i=0;i<(j/2);i++) 
  {
    temp      = myword[i];
    myword[i] = myword[j];
    myword[j] = temp; 

    j--; 
  }
}

推荐答案

尽管这看起来很像功课,但我可以建议:

Despite this looking quite homeworky, may I suggest:

void reverse(char word[])
{
    int len=strlen(word);
    char temp;
    for (int i=0;i<len/2;i++)
    {
            temp=word[i];
            word[i]=word[len-i-1];
            word[len-i-1]=temp;
    }
}

或者,更好的是,经典的 XOR 实现:

or, better yet, the classic XOR implementation:

void reverse(char word[])
{
    int len=strlen(word);
    for (int i=0;i<len/2;i++)
    {
        word[i]^=word[len-i-1];
        word[len-i-1]^=word[i];
        word[i]^=word[len-i-1];
    }
}

这篇关于C++ 反向数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆