繁体   English   中英

C中的字符串反向程序

[英]string reverse program in C

我已经写了一个程序来反转一个字符串..但它不工作..它是打印扫描相同的字符串..代码有什么问题?

#include <stdio.h>
#include <stdlib.h>
char *strrev(char *s)
{
        char *temp = s;
        char *result = s;
        char t;
        int l = 0, i;
        while (*temp) {
                l++;
                temp++;
        }
        temp--;
        for (i = 0; i < l; i++) {
                t = *temp;
                *temp = *s;
                *s = t;
                s++;
                temp--;
        }
        return result;
}

int main()
{
        char *str;
        str = malloc(50);
        printf("Enter a string: ");
        scanf("%s", str);
        printf("%s\n\n", strrev(str));
        return 0;
}
for (i = 0; i < l; i++)

你正在穿过整个弦乐,所以你要反转它两次 - 毕竟它不会被逆转。 只走一半:

for (i = 0; i < l / 2; i++)

此外,如果您被允许这样做,请尝试使用int len = strlen()而不是while-not-end-of-string循环。

您交换字符串的内容两次。

使用以下代码..

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>

char *strrev(char *s)
{
     char *temp = s;
     char *result = s;
     char t;
     while (*temp)
          temp++;

     while (--temp != s)
     {
            t = *temp;
            *temp = *s;
            *s++ = t;
     }
     return result;
 }

 int main()
 {
      char *str;
      str = (char*)malloc(50);
      printf("Enter a string: ");
      scanf("%s", str);
      printf("%s\n\n", strrev(str));
      return 0;
  }

逻辑是将字符从开始到上半部分与下半部分的最后一个字符交换,即高达len / 2。 只需修改你的for循环,如下所示它将适合你(i = 0; i <l / 2; i ++){

你可以使用这个简单的代码

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>


int str_len (char *str)
{
   char *ptr = str;
    while (*str)
     str++;
   return str - ptr;
}

int main ()
{
  char *str;
  int length;
  str = (char*)malloc(50);
  printf("Enter a string: ");
  scanf("%s", str);
  length = str_len(str) - 1;

  for (int i = length ; i >= 0 ; i--)
  printf ("%c", str[i]);
  return 0;
}

实际上你正在反转字符串两次...所以在到达字符串的中间之后,你应该终止循环,你的循环应该运行一半的字符串长度是l / 2(在这种情况下)。 所以你的循环应该是这样的

for(i = 0; i < i / 2; i++)

交换字符串内容两次..

交换一次将有助于..

for (i = 0; i < l/2; i++)
you can use this code to reverse the string
#include<stdio.h>
#include<string.h>
int main()
{
    int n,i;
    char str2[100],str1[100];
    printf("enter teh string 1\n");
    gets(str1);
    n = strlen(str1);
    for(i=0;i<n;i++)
    {
    str2[n-1-i]=str1[i];
    }
    printf("%s\n",str2);

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM