在自己的位置反转一个字符数组

我在接受采访时被问到这个问题

我原本应该在自己的位置反转字符数组而不是反转整个字符数组.

如果

char *ch="krishna is the best";

然后我应该以这样的方式反转,输出应该是这样的

anhsirk si eht tseb

我无法在面试中编写代码.任何人都建议我如何写这样做.

可以在指针的帮助下完成吗?

如果面试官没有告诉我将其反转到自己的位置,那么如果使用另一个数组字符数组很容易处理,那么在反转它之后会有新的字符串吗?

解决方法

char *ch="krishna is the best";

不可以,这是一个指向只读字符串文字的指针.让我们想象一下,你的面试官知道C并写下了这个:

char str[]="krishna is the best";

然后你可以做这样的事情:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

char* str_reverse_word (char* str)
{
  char* begin;
  char* end;
  char* the_end;
  char  tmp;

  while(isspace(*str)) /* remove leading spaces from the string*/
  {
    str++;
  }

  begin = str;
  end = str;


  while(!isspace(*end) && *end != '\0') /* find the end of the sub string */
  {
    end++;
  }
  the_end = end; /* save this location and return it later */
  end--; /* move back 1 step to point at the last valid character */


  while(begin < end)
  {
    tmp = *begin;
    *begin = *end;
    *end = tmp;

    begin++;
    end--;
  }

  return the_end;
}

void str_reverse_sentence (char* str)
{
  do
  {
    str = str_reverse_word(str);
  } while (*str != '\0');
}

int main (void)
{
  char str[]="krishna is the best";
  str_reverse_sentence (str);
  puts(str);
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...