C++ Reverse Array

后端 未结 4 741
北恋
北恋 2020-12-01 20:22

In C++, I need to:

  • Read in a string from user input and place it into a char array [done]
  • Then pass that array to a function [done]
  • The funct
相关标签:
4条回答
  • 2020-12-01 20:33

    If we are talking C-Strings, then your function should be

    void reverse(char word[],size_t wordlen)
    

    First answer from the same question (this is a dupe from Reverse a sentence in C?)

    This doesn't do what you are looking for, but gets you quite close!

     int ReverseString(char *rev)
             {
                if(*rev!='\0')
                {
                   ReverseString(rev + 1);
                   putchar(*rev);//change this.
                }
    
                return 1;
             }
    

    Credits to @devinb.

    0 讨论(0)
  • 2020-12-01 20:41

    //this program helps you to find maximum and minimum number in an array

    #include<iostream.h>
    #include<conio.h>
    int main()
    {int max;
    
        int a[5]={12,1,0,4,5};
     int min=a[0];
        int i=1;
        max=a[0];
    
        while(i<=4)
        {
                  if (max < a[i])
                  max=a[i];
                  if (min > a[i])
                  min=a[i];
                  i++;
    
        }
                  cout << min <<"\n";
                  cout << max;
                  getch();
                  return 0;
    }              
    
    0 讨论(0)
  • 2020-12-01 20:42

    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;
        }
    }
    

    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];
        }
    }
    
    0 讨论(0)
  • 2020-12-01 20:45

    Since this is homework, I'll point you toward a solution without just giving you the answer.

    Your reverse function can modify the word that is passed in. One thing you'll need to know is how long the word is (so you'll know how many letters to reverse), you can get this from the strlen() function. If you're not permitted to use pointers, then you can use a local int index variable.

    0 讨论(0)
提交回复
热议问题