Java教程

1-19 编写函数reverse(s),将字符串s中的字符顺序颠倒过来。使用该函数编写一个程序,每次颠倒一个输入行中的字符顺序

本文主要是介绍1-19 编写函数reverse(s),将字符串s中的字符顺序颠倒过来。使用该函数编写一个程序,每次颠倒一个输入行中的字符顺序,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

/*编写函数reverse(s),将字符串s中的字符顺序颠倒过来。使用该函数编写一个程序,每次颠倒一个输入行中的字符顺序*/
#include<stdio.h>
#define MAXLINE 1000
int getline(char line[], int maxline);
void reverse(char s[]);

int main() {
char line[MAXLINE];
while (getline(line,MAXLINE)>0) {
reverse(line);
printf("%s\n", line);
}
return 0;
}
// getline函数: 讲一行读入到S中,并返回其长度
int getline(char s[], int lim) {
int c, i;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if (c=='\n'){
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
void reverse(char s[]) {
int i, j;
char temp;
i = j = 0;
temp = '\0';
//find the end of string s
while (s[i] != '\0')
++i;
--i;
if (s[i] == '\n')
--i;
//swap the characters
while (j < i) {
temp = s[j];
s[j] = s[i];
s[i] = temp;
--i;
++j;
}
}

这篇关于1-19 编写函数reverse(s),将字符串s中的字符顺序颠倒过来。使用该函数编写一个程序,每次颠倒一个输入行中的字符顺序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!