反转字符串并计算 C 中反转的字符数 [英] Reversing a string and counting the number of characters that were reversed in C

查看:70
本文介绍了反转字符串并计算 C 中反转的字符数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的教授已经开始编写代码,看起来像......

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)
{

}

现在我应该完成它,这就是我被卡住的地方.我已经查找了无数个反转字符串的示例程序,但所有示例程序的完成方式都不同,我不知道如何将其转换"为我的教授为我们布置的代码的适当上下文.我也对int argc"应该是什么感到困惑.但是,我想在计算和返回反向字符数时,我可以简单地输入这样的内容 for(int length=0; str[length]!='\0';length++); 但除此之外,我很难过.

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.

推荐答案

如果您担心函数 reverseString() 将返回什么,您将反转整个字符串.所以,如果字符串的长度是偶数,函数应该返回length,如果长度是奇数,它应该返回length-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;
}

这篇关于反转字符串并计算 C 中反转的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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