如何反向字符串c [英] how Reverse string c

查看:341
本文介绍了如何反向字符串c的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好我想在c中使用反向字符串(string.h :( strcat和strcpy和strcmp))

没有(poniter和strrev)

抱歉我的英语

我希望这些不答案

hello i want Reverse string in c just using (string.h :(strcat and strcpy and strcmp))
without (poniter and strrev )
sorry for my english
I want these non- answer

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
void reverse (int index, char *str ) ;
int main (void)
{
   char name[100];
   printf ("Enter a mutli-word string") ;
   gets(name) ;
   reverse (strlen(name) , name ) ;
}
void reverse (int index, char *str )
{
  if (--index < 0 )
  {
     return ;
  }
  else
  {
        putchar ( *(str + index) ) ;
       reverse (index, str) ;
  }
}

推荐答案

目前尚不清楚储备是什么意思。这可能是一个错误/错字。



但是,对没有指针和数组的字符串做任何事情听起来都很荒谬。为什么?仅仅因为 C字符串本身就是一个指针;和一个数组同时



也许你没有正确地表达问题。在不同的考试和访谈中经常会出现一个流行的问题:给定一个C字符串,修改它以反向排列其字符,而不使用另一个内存区来存储字符串。就是这样,使用与源字符串相同的内存区域,使用表示中间字符或指针的一两个自动变量就足够了。问题是可以解决的,但具有不同程度的优雅。如果这是一个有问题的问题,我们可以讨论它,但是只要你显示 你尝试了什么 所以远。



-SA
It is not clear what do you mean by "reserve". It's possible that this is a mistake/typo.

However, doing anything to a string "without pointer and array" just sounds absurd. Why? Simply because a C string itself is a pointer; and an array at the same time.

Perhaps you just did not formulate the problem correctly. There is a popular problem often offered during different exams and interviews: given a C string, modify it to rearrange its characters in reverse order, without using another area of memory to store the string. That's it, it should be enough to have one-two auto variables representing intermediate characters or pointers, using the same memory area as the one of the source string. The problem is quite solvable, but with different degree of elegance. If that is a problem are interested in, we can discuss it, but no sooner than you show what have you tried so far.

—SA


这是否满足您的约束条件?

Is this fulfilling your constraints?
size_t pos = strlen(name);
while(pos > 0) putchar(name[--pos]);

干杯

Andi

Cheers
Andi


较新的解决方案



我认为这更接近你的要求吗?



Newer solution

I think this is closer to your requirements?

void reverse (int len, char *str )
{
    char *tmp=(char*)calloc(len, sizeof(char));
    const char *p=0;
    while(len--)
    {
        p=(str+len);
        strncat(tmp, p, 1);
    }

    strcpy(str,tmp);
    free(tmp);
}





以前的解决方案



我试着没有指针,但最好的解决了。





Previous solution

I tried to do without pointers, but this best I work out.

void reverse (int len, char *str )
{
    char rev[100];
    memset(rev,0,100*sizeof(char));
    int i=len;
    const char* p;
    while(i)
    {
        p=str+i-1;
        strcat(rev, p);
        *(str+i-1)='\0';
        i--;
    }
    strcpy(str,rev);
}


这篇关于如何反向字符串c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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