11、输入字符颠倒输出
1 #include <stdio.h> 2 #define MAXLENGTH 1000 3 4 /* 5 颠倒输入字符串顺序 6 1、获取并存储字符串 7 2、获取字符串长度 8 3、首尾交换 9 4、起始位置+1,终止位置-1 10 5、首位交换 11 6、3-4-5循环 12 */ 13 14 int getline(char line[]); 15 void reverse(char line[], int length); 16 17 int main() 18 { 19 int i; 20 int length; 21 char line[MAXLENGTH]; 22 23 for (i=0; i<MAXLENGTH; ++i) //初始化存储数组 24 { 25 line[i] = '\0'; 26 } 27 28 length = getline(line); //获取输入内容长度 29 30 if (length < 1) 31 printf("未输入内容!\n"); //长度判断 32 else 33 { 34 reverse(line, length); 35 printf("顺序颠倒后输入内容为:%s\n", line); 36 } 37 38 return 0; 39 } 40 41 int getline(char line[]) 42 { 43 int i; 44 int c; 45 46 i = 0; 47 48 while ((c=getchar()) != EOF && c != '\n') 49 { 50 line[i] = c; 51 ++i; 52 } 53 54 return i; //返回输入长度,此处长度值为实际长度,比数组下标多1 55 } 56 57 void reverse(char line[], int length) 58 { 59 int i; 60 int temp; 61 62 --length; //在顺序调换时,把长度值-1,使其与实际数组下标保持一致 63 64 for (i=0; i<length; ++i) 65 { 66 temp = line[i]; //先将首字符额外取出 67 line[i] = line[length]; //将尾字符调换至首字符位置 68 line[length] = temp; //将首字符调换至尾字符位置 69 --length; //字符数组长度-1 70 } 71 }
//多行输入,行内连续调换输出
1 #include <stdio.h> 2 #define MAXLENGTH 1000 3 4 int getline(char line[]); 5 void reverse(char line[], int length); 6 int start; 7 8 int main() 9 { 10 int i; 11 int length; 12 char line[MAXLENGTH]; 13 14 start = 0; 15 16 for (i=0; i<MAXLENGTH; ++i) 17 { 18 line[i] = '\0'; 19 } 20 21 length = getline(line); 22 23 if (length < 1) 24 printf("未输入内容!\n"); 25 else 26 { 27 for (i=0; line[i]!='\0'; ++i) 28 { 29 while (line[i] == '\n') 30 { 31 length = i; 32 reverse(line, length); 33 start = i+1; 34 ++i; 35 } 36 } 37 printf("顺序颠倒后输入内容为:\n%s\n", line); 38 } 39 40 return 0; 41 } 42 43 int getline(char line[]) 44 { 45 int i; 46 int c; 47 48 i = 0; 49 50 while ((c=getchar()) != EOF) 51 { 52 line[i] = c; 53 ++i; 54 } 55 56 return i; 57 } 58 59 void reverse(char line[], int length) 60 { 61 int temp; 62 63 --length; 64 65 for (; start<length; ++start) 66 { 67 temp = line[start]; 68 line[start] = line[length]; 69 line[length] = temp; 70 --length; 71 } 72 }