简体   繁体   English

字符串反转,循环和数组在c中

[英]string reverse with loop and array in c

I just want to reverse a string using for loop and array. 我只想使用for循环和数组来反转字符串。 Don't want to use any predefined function. 不想使用任何预定义的功能。 I used the following code but its near to nothing. 我使用了以下代码,但它几乎没有。 Please share some good suggestions. 请分享一些好的建议。

int main(){
char a[]="this is a man";
char b[30];
int p= sizeof(a)/sizeof(a[0]);
for(int i=p-1;i>0;i--){
    for(int j=0;j<p;j++){

   b[j]=a[i];
     }
    }

 printf("array is %s",b);
 return 0;
}
#include<stdio.h>

int main(){

char str[] = "str to rev";
char revstr[12]={'\0'};
int i, j;
int length = strlen(str);
j = 0;
for(i = length-1; i>=0; i--){
  revstr[j] = str[i];
  j = j + 1;
}

printf("%s", revstr);

return 0;
}

1) In your first for loop, you have to reach 0 ( i>=0 ) 1)在你的第一个for循环中,你必须达到0( i>=0

for(int i=p-1;i>=0;i--){

2) The a[p-1] contains the null termination( '\\0' ) of your string a[] . 2) a[p-1]包含字符串a[]的空终止( '\\0' )。 And the null termination should not be included in the array reverse procedure. 并且空终止不应包含在数组反向过程中。 So in your first loop you should start from p-2 and not from p-1 . 所以在你的第一个循环中你应该从p-2而不是从p-1

And after finishing the reversing you have to add a '\\0' (null terminator) at the end of your b array 完成反转后,你必须在b数组的末尾添加一个'\\0' (空终止符)

b[j]='\0'; // add this
printf("array is %s",b);
return 0;

3) And as said in the other answers, you have to use only one loop and not 2 loops. 3)正如在其他答案中所说,你必须只使用一个循环,而不是2个循环。

int i,j;
for (i=p-2, j=0; i>=0; i--,j++) {
    b[j]=a[i];
}
b[j]='\0';
printf("array is %s",b);

Using while loop:: 使用while循环::

void main()
{
 char str[100],temp;
 int i,j=0;

 printf("nEnter the string :");
 gets(str);

 i=0;
 j=strlen(str)-1;

 while(i<j)
     {
     temp=str[i];
     str[i]=str[j];
     str[j]=temp;
     i++;
     j--;
     }

 printf("nReverse string is :%s",str);
 return(0);
}

Using for loop:: 使用for循环::

void StrRev(char *str)
{
 int i, len, endpos;

 len = strlen(str);
 endpos = len-1;

 for(i = 0; i < len / 2; i++)
 {
   char temp = str[i];
   str[i] = str[endpos - i];
   str[endpos - i] = temp ;
 }
}

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

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