我已经搜索并阅读了几天试图解决此问题。
我只是想用自己的函数来反转C中的字符串,但我现在很难过,并且在2天内无法继续前进!
这是我的代码:
/*
This program takes a string
as input and returns it to
the user but in reverse order.
*/
#include "stdio.h"
#include "stdlib.h"
#define MAXLINE 1000
/* Take in a string and return its length. */
int getline(char s[]);
/* Copy From to To. */
void copy(char To[], char From[]);
/* Take the contents of a string and reverse them. */
char * reverse(char s[]);
int main() {
char mainString[MAXLINE + 1];
copy(mainString, "Test string.");
printf("Your string before reversal: %s\n", mainString);
reverse(mainString);
printf("Your string after reversal: %s\n", mainString);
return 0;
}
int getline(char s[]) {
int i;
for(i = 0; s[i] != '\0'; i++);
i++;
return i;
}
void copy (char To[], char From[]) {
int i;
for(i = 0; From[i] != '\0'; i++) {
To[i] = From[i];
};
To[i] = '\0';
}
char * reverse(char s[]) {
int string_length;
string_length = getline(s);
char myString[MAXLINE];
int a = 0;
int i;
i = string_length;
while (i >= 0) {
s[i] = myString[a];
a++;
i--;
};
copy(s, myString);
return s;
}
答案 0 :(得分:2)
在getline函数的末尾删除i ++。这导致返回的字符串长度比它应该多1,这反过来导致了一个' \ 0'成为你的反向弦的第一个字符,不应该发生。
此外,该行
s[i] = myString[a];
错了。这会改变s,但你想改变myString:
myString[i] = s[a];
(或者,您可以复制(myString,s);在while循环之前填充myString,然后将数据从那里复制回s。)
答案 1 :(得分:1)
修复
int getline(char s[]) {
int i;
for(i = 0; s[i] != '\0'; i++);
return i;
}
char * reverse(char s[]) {
int string_length;
string_length = getline(s);
char myString[MAXLINE];
int i, a =0;
i = string_length-1;
while (i >= 0) {
myString[a]=s[i];
a++;
i--;
}
myString[a] ='\0';
copy(s, myString);
return s;
}
答案 2 :(得分:0)
reverse函数需要反转参数中传递的字符串s,myString是带有垃圾字符的本地字符串
所以你不能做一个
s [i] = myString [a]
你只是松开了s
中的所有字符