我已经搜索和阅读了几天试图解决这个问题。
我只是想用我自己的函数来反转 C 中的一个字符串,但我现在很难过,两天后都无法前进!
这是我的代码:
/*
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;
}