微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

如果

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐