[英]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.