練習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".spa
練習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-3code
/* 複製字符串 */ #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-4blog
#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-6string
#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-7io
/* 對字符串中的英文字符進行大小寫轉換 */ #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-8class
#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); }