Reversing a string and counting the number of characters that were reversed in C

荒凉一梦 提交于 2019-12-11 04:37:23

问题


My professor already got started on the code and it looks like...

#include "stdafx.h"

int main(int argc, char* argv[])
{
    int numchar;

    char mystring[] = "This is the string to be printed  in reverse order";
    numchar = reverseString(mystring);

    puts("Reversed String is  ");
    puts(mystring);
}
int reverseString(char *mystring)
{

}

Now I'm supposed to finish it and that's where I'm stuck. I've looked up countless example programs of reversing strings but all of them were done differently and I'm lost on how to "convert" it into the appropriate context of the code that my professor has laid out for us. I'm also confused on what 'int argc' is supposed to be. However, I figured when it comes to counting and returning the number of characters reversed, I can simply put in something like this for(int length=0; str[length]!='\0';length++); but other than that, I'm stumped.


回答1:


If you are worried on just what the function reverseString() is going to return, you are going to reverse the entire string. So, if the length of the string is even, the function should return the length and if the length is odd, it should return length-1

Other than that, from your question, it is the usual string reverse function.

int reverseString(char *string) 
{
   int length, c;
   char *begin, *end, temp;

   length = string_length(string);

   begin = string;
   end = string;

   end += length - 1;    
   while(begin<end){
      temp = *end;
      *end = *begin;
      *begin = temp;

      begin++;
      end--;
   }
   if(length % 2 == 0) return length;
   else return length-1;
}

int string_length(char *pointer)
{
   int c = 0;

   while( *(pointer+c) != '\0' )
      c++;

   return c;
}


来源:https://stackoverflow.com/questions/14525527/reversing-a-string-and-counting-the-number-of-characters-that-were-reversed-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!