练习11-1
/* 用指针实现的字符串的改写 */ #include <stdio.h> int main(void) { char* p = "123"; printf("p = \"%s\"\n", p); p = "456"+1; /* OK! */ printf("p = \"%s\"\n", p); return 0; }
只能输出“56”,因为p指向的地址+1后,整体往后移了一位,所以读到的内容从“456”变成了“56\0".
练习11-2
/* 字符串数组 */ #include <stdio.h> int main(void) { int i; char a[][128] = { "LISP", "C", "Ada" }; char* p[] = { "PAUL", "X", "MAC","SKTNB"};//用 sizeof(a) / sizeof(a[0])表示数组元素个数 for (i = 0; i <( sizeof(a) / sizeof(a[0]));i++) printf("a[%d] = \"%s\"\n", i, a[i]); for (i = 0; i < (sizeof(p) / sizeof(p[0])); i++) printf("p[%d] = \"%s\"\n", i, p[i]); return 0; }
练习11-3
/* 复制字符串 */ #include <stdio.h> /*--- 将字符串s复制到d ---*/ char* str_copy(char* d, const char* s) { char* t = d; while (*d++ = *s++) ; return t; } int main(void) { char str[128] = "ABC"; char tmp[128]; printf("str = \"%s\"\n", str); printf("复制的是:", tmp); scanf("%s", tmp); puts("复制了。"); printf("str = \"%s\"\n", str_copy(str, tmp)); return 0; }
练习11-4
#include <stdio.h> void put_string(const char* s) { putchar(*s); while (*s++) { putchar(*s); } } int main() { char s[123] ; printf("请输入字符串:"); scanf("%s",s); put_string(s); }
练习11-5
#include <stdio.h> int str_chnum(const char* s,int c) { int cnt = 0; while (*s != NULL) { if (*s == c) { cnt++; } *s++; } return cnt; } int main() { char s[123] ; char c ; printf("要计数的字符是:"); scanf("%c", &c); printf("请输入字符串:"); scanf("%s",s); printf("%d", str_chnum(s, c)); }
练习11-6
#include <stdio.h> char *str_chnum(const char* s,int c) { while (*s++) { char* t = s; if (*s == c) { return t; break; } } return NULL; } int main() { char s[123] ; char c ; printf("要计数的字符是:"); scanf("%c", &c); printf("请输入字符串:"); scanf("%s",s); printf("%s", str_chnum(s, c)); }
练习11-7
/* 对字符串中的英文字符进行大小写转换 */ #include <ctype.h> #include <stdio.h> /*--- 将字符串中的英文字符转为大写字母 ---*/ void str_toupper(char *s) { while (*s) { *s = toupper(*s); *s++; } } /*--- 将字符串中的英文字符转为小写字母 ---*/ void str_tolower(char *s) { while (*s) { *s = tolower(*s); *s++; } } int main(void) { char str[128]; printf("请输入字符串:"); scanf("%s", str); str_toupper(str); printf("大写字母:%s\n", str); str_tolower(str); printf("小写字母:%s\n", str); return 0; }
练习11-8
#include <stdio.h> #include<stdlib.h> int strtoi( const char* nptr ) { int sign = 1, num = 0; if (*nptr == '-') { sign = -1; nptr++; } while (*nptr) { num = num * 10 + (*nptr - '0'); nptr++; } return num * sign; } int main() { char c[128]; printf("请输入字符串:"); scanf("%s", c); int m = strtoi(c); printf("%d",m); }