[英]reversing the string without any predefined function in c
我正在使用下面的代碼,我不知道我做錯了什么。
#include <stdio.h>
void main()
{
char a[5];
char ptr[5] = "hello";
int i,j,k=0;
for(i=0;ptr[i] !='\0'&&ptr[i]!=' ';i++){}
k=i;
for(j=0;j<=i;j++)
{
a[j] = ptr[k];
printf("%c %c %d %d %d\n",a[j],ptr[k],i,j,k);
k--;
}
printf("%s %s",a,ptr);
}
Output:
5 0 5
o o 5 1 4
l l 5 2 3
l l 5 3 2
e e 5 4 1
h h 5 5 0
hello
我想這就是你要找的。
#include <stdio.h>
int main()
{
char a[6];
char ptr[6] = "hello";
int i,j,k=0;
for(i=0;ptr[i] !='\0'&&ptr[i]!=' ';i++){}
k= i - 1;
for(j=0;j<i;j++)
{
a[j] = ptr[k];
printf("%c %c %d %d %d\n",a[j],ptr[k],i,j,k);
k--;
}
printf("%s %s",a,ptr);
}
我已經針對輸入字符串的未定義長度編輯了我的答案。 看一看:
#include <stdio.h>
#include<string.h>
void main(){
char a[10];
char ptr[10];
scanf("%s", ptr);
for(int i = 0, j = strlen(ptr)-1; j != -1; i++, j--){
a[i] = ptr[j];
}
printf("%s", a);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.