实验六
task 1
1.2004
2.2001
3.指针指向类型不同,前者指向int型,++p加 sizeof(int)=4
task 2
1.2004 2004
2.2001 2001
task 3
1.sizeof 计算实际分配的内存数,包含'\0' strlen计算字符个数不包含\0
2.不可以
3.交换的地址 是
task 4
#include <stdio.h> #include <string.h> #define N 5 int check_id(char *str); // 函数声明 int main() { char *pid[N] = {"31010120000721656X", "330106199609203301", "53010220051126571", "510104199211197977", "53010220051126133Y"}; int i; for (i = 0; i < N; ++i) if (check_id(pid[i])) // 函数调用 printf("%s\tTrue\n", pid[i]); else printf("%s\tFalse\n", pid[i]); return 0; } // 函数定义 // 功能: 检查指针str指向的身份证号码串形式上是否合法。 // 形式合法,返回1,否则,返回0 int check_id(char *str) { if (strlen(str) != 18) return 0; int flag = 1; while (*++str) { if (*str >= '0' && *str <= '9' || *str == 'X') ; else flag = 0; } return flag; }
task 5
#include <stdio.h> #include <string.h> #define N 80 int is_palindrome(char *s); // 函数声明 int main() { char str[N]; int flag; printf("Enter a string:\n"); gets(str); flag = is_palindrome(str); // 函数调用 if (flag) printf("YES\n"); else printf("NO\n"); return 0; } // 函数定义 // 功能:判断s指向的字符串是否是回文串 // 如果是,返回1;否则,返回0 int is_palindrome(char *s) { int flag = 1; char *p = s; while (*++p) ; p--; for (int i = 0; i < strlen(s) / 2; i++) { if (*p-- == *s++) ; else flag = 0; } return flag; }
task 6
#include <stdio.h> #define N 80 void encoder(char *s); // 函数声明 void decoder(char *s); // 函数声明 int main() { char words[N]; printf("输入英文文本: "); gets(words); printf("编码后的英文文本: "); encoder(words); // 函数调用 printf("%s\n", words); printf("对编码后的英文文本解码: "); decoder(words); // 函数调用 printf("%s\n", words); return 0; } /*函数定义 功能:对s指向的字符串进行编码处理 编码规则: 对于a~z或A~Z之间的字母字符,用其后的字符替换; 其中,z用a替换,Z用A替换 其它非字母字符,保持不变 */ void encoder(char *s) { while (*s) { if (*s >= 'a' && *s <= 'y' || *s >= 'A' && *s <= 'Y') *s = *s + 1; else if (*s == 'z') *s = 'a'; else if (*s == 'Z') *s = 'A'; else ; s++; } } /*函数定义 功能:对s指向的字符串进行解码处理 解码规则: 对于a~z或A~Z之间的字母字符,用其前面的字符替换; 其中,a用z替换,A用Z替换 其它非字母字符,保持不变 */ void decoder(char *s) { while (*s) { if (*s >= 'b' && *s <= 'z' || *s >= 'B' && *s <= 'Z') *s = *s - 1; else if (*s == 'a') *s = 'z'; else if (*s == 'A') *s = 'Z'; else ; s++; } }