简体   繁体   English

在没有库函数的情况下反转c中的字符串

[英]reversing a string in c without library function

In this program I am trying to take a string as input from the user guessing that the maximum length of the string here is 40 (obviously can exceed). 在这个程序中,我试图从用户输入一个字符串作为输入,猜测这里字符串的最大长度是40(显然可以超过)。

I'm finding out the length and using the length to create another character array dynamically( only to prevent assigning this array with any random value) and finally, adding the characters from the last to get the reversed string. 我找出长度并使用长度动态创建另一个字符数组(仅防止为此数组分配任何随机值),最后,添加最后一个字符以获取反向字符串。

It compiles just fine, but upon running, provides no output. 它编译得很好,但在运行时,不提供任何输出。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    char word[40];
    char *rev;
    int i=0;
    int l=0;
    printf("Enter any statement \n");
    scanf("%[^\n]", word);
    while(word[i]!='\0')
    {
        i++;
    }
    // i contains  the length of the string
    rev=(char *)malloc(i*sizeof(char));
    while(i>0)
    {
        rev[l]=word[i];
        i--;
        l++;
    }
    printf("\n %s", rev);
    return 0;
}

You have two (at least) problems: The first one is that you swap characters twice . 你有两个(至少)问题:第一个是你交换两次字符。 The second problem is that you also include the terminator character in your swapping. 第二个问题是您还在交换中包含终止符。

我相信你有一个'一次性'类型的错误,并没有看到任何输出,因为teminating \\0字符被复制到rev的第一个位置。

rev[l]=word[i]; should rev[l]=word[i-1]; 应该rev[l]=word[i-1];

Point 1:- 第1点: -

In C a string is always ended with '\\0' (NULL Termination),you should always manually insert a '\\0' at the end,which i think you forgot.But no worries even i did not remember it as well when i started...:) ,Experiences like these will make you from next time. 在C中,一个字符串总是以'\\0'结尾 (NULL终止),你应该总是在结尾处手动插入一个'\\0' ,我想你已经忘记了。但不用担心即使我也不记得它当我开始...... :),这些经历会让你从下次开始。

Point 2:- 第2点: -

Assume you have a string char str[]="ABCD" ; 假设你有一个字符串char str[]="ABCD" ; ,In memory this would look like this ,在内存中,这将是这样的

   ------------IN Memory----------------
  | 'A' || 'B' || 'C' | | 'D' | | '\0' |      
   -------------------------------------
     0      1      2       3        4  

Just by looking we can say that its length would be 4 (we know that we don't include '\\0' when calculating length) . 只是看看我们可以说它的长度是4 (我们知道在计算长度时我们不包括'\\0' For copying in reverse we need to start with character 'D' whose index is 3 ,that means you have to start copying from 2nd last character whose index can be can be found from length of string -1 .The mistake you did in your above program is you have used length of string (which is 4), to start copying.which copies '\\0' as first character in rev[] ,Hence it provides no output. 对于反向复制,我们需要从索引为3的字符'D'开始,这意味着你必须从第二个字符开始复制,其索引可以从字符串-1的长度找到。你在上面做的错误程序是你使用字符串的长度(即4),开始复制'\\0'它将'\\0'复制为rev[]第一个字符,因此它不提供输出。

Other points:- 其他要点: -

Based on the above two points i have corrected the mistakes, see comments in the below program to understand it well.And i have used int j; 基于以上两点,我已经纠正了错误,请参阅下面的程序中的注释以便理解它。并且我使用了int j; instead of int l; 而不是int l; because i felt so confusing. 因为我感到很困惑。 and please use width specifier when reading strings using scanf(); 并且在使用scanf();读取字符串时使用宽度说明符scanf(); In your while loop, you should change the condition from i>0 to i>=0 because when i reaches 0, i>0 condition will break the loop before copying the first character from word[] to rev[] . 在while循环中, 您应该将条件从i>0更改为i>=0因为当i达到0时, i>0条件将在将第一个字符从word[]复制到rev[]之前中断循环。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
   char word[40];
   char *rev;
   int i=0;
   int j=0;
   printf("Enter any statement \n");
   scanf("%39[^\n]", word);//using width specifier,(POINT 1)here 39 because sizeof(word)-1, one left to accommodate '\0' at end.

    while(word[i]!='\0')//calculating length of string
    {
       i++;
    }
    rev=(char *)malloc(i*sizeof(char)+1);// (POINT 1),here making +1 to accommodate '\0' at end.

    i=i-1;//(POINT 2)- Last index of the array is always length of string - 1

   while(i>=0)//This should be i>=0 because you also want to copy first character of input string.
   {
       rev[j]=word[i];
       i--;
       j++;
   }
   rev[j]='\0';//(POINT 1) You should end with '\0'.
   printf("\n %s", rev);
return 0;
}

Your scanf format string looks weird. 您的scanf格式字符串看起来很奇怪。 Perhaps you are using some strange feature of it that I'm unaware of, so I'll pass on that. 也许你正在使用它我不知道的一些奇怪的功能,所以我会传递它。 But you need to make sure that word is a null terminated string after the user input is done. 但是,在完成用户输入后,您需要确保该word是以空字符结尾的字符串。

while(word[i]!='\0')

This loops counts until it finds the null term. 此循环计数, 直到找到空项。 So i will contain the string length: you just invented the strlen() function. 所以i将包含字符串长度:你刚刚发明了strlen()函数。 It will not contain the string length plus the null terminator length (1). 它不包含字符串长度加上空终止符长度(1)。

Therefore 因此

rev=(char *)malloc(i*sizeof(char));

is incorrect, you need to allocate i+1 bytes. 不正确,你需要分配i + 1个字节。

Also, you shouldn't cast the result of malloc, because doing so is completely pointless. 此外,你不应该转换malloc的结果,因为这样做是完全没有意义的。

And when you copy, you have to ensure that you also copy the null terminator. 复制时,必须确保复制空终止符。

The code has several memory mistakes and using static memory is also an issue. 代码有几个内存错误,使用静态内存也是一个问题。 But for if you are using for practice purpose below are the changes and its explanation. 但是,如果您正在使用以下练习目的,则更改及其解释。

i--; // you can't place a '\0' to your rev[0] else it would always be NULL string when you print
while(i>=0)
{
    rev[l]=word[i];
    i--;
    l++;
}
    rev[l]='\0'; // string should be terminated by '\0'
printf("\n%s\n", rev);

Below code with just one modification should return just correct answer. 只需一次修改的代码下面应该返回正确的答案。 I changed in 2nd while loop from: 我改变了第二次循环来自:

rev[l]=word[i]; 转[1] =字[I];

to

rev[l]=word[i-1]; 转[1] =字[I-1];

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    char word[40];
    char *rev;
    int i=0;
    int l=0;
    printf("Enter any statement \n");
    scanf("%[^\n]", word);
    while(word[i]!='\0')
    {
        i++;
    }
    // i contains  the length of the string
    rev=(char *)malloc(i*sizeof(char));
    while(i>0)
    {
        rev[l]=word[i-1];
        i--;
        l++;
    }
    printf("\n %s", rev);
    return 0;
}
 //Reverse of a string without using string functions 

 #include<stdio.h>
 #include<conio.h>
 void main()
  {
  char a[40];
  int j=0,len=0;
  clrscr();
  printf("please enter your name\n");
  gets(a);              // takes white spaces as characters
  printf("the reverse of your name is\n");
  while (a[j]!=NULL)    // finding the length of the string array
   {
    len++;
    j++;
   }
  for(int k=len;k>=0;k--) 
   {
    printf("%c",a[k]);
   }
  getch();
 }

Output - please enter your name 输出 - 请输入您的姓名

     dwayne rock johnson 

     the reverse of your name is

     nosnhoj kcor enyawd

As noted, array indices begin at zero and end at length-1. 如上所述,数组索引从零开始并以长度-1结束。 Moreover, if you like, you could rewrite your code in a more cryptic fashion: 此外,如果您愿意,可以用更加神秘的方式重写代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
  char word[40];
  char *rev;
  int i=0;
  int l=0;
  printf("Enter any statement \n");
  scanf("%[^\n]", word);

  while(word[++i]);

  // i contains  the length of the string 
  rev=(char *)malloc(i*sizeof(char));
  while(rev[l++]=word[i---1], i>0);
  printf("%s\n", rev);
  return 0;
}

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

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