[关闭]
@yanglt7 2019-02-21T11:40:47.000000Z 字数 4037 阅读 891

第9周:字符串

C


9.1.1 字符串:字符串

字符数组

字符串

字符串变量

字符串常量

字符串总结

9.1.2 字符串:字符串变量

字符串常量

char * s = "Hello,world!";

指针还是数组?

char* 是字符串?

9.1.3 字符串:字符串的输入输出

字符串赋值?

字符串输入输出

安全输入

常见错误

空字符串

9.1.4 字符串:字符串数组,以及程序参数

字符串数组

程序参数

9.2.1 字符串函数:单字符输入输出

putchar

9.2.2 字符串函数:字符串函数strlen

string.h

strlen

  1. #include <stdio.h>
  2. #include <string.h>
  3. size_t mylen(const char *s)
  4. {
  5. int idx = 0;
  6. while(s[idx] != '\0') {
  7. idx++;
  8. }
  9. return idx;
  10. }
  11. int main(int argc, char const *argv[])
  12. {
  13. char line[] = "Hello";
  14. printf("strlen=%lu\n", mylen(line));
  15. printf("sizeof=%lu\n", sizeof(line));
  16. return 0;
  17. }
  18. strlen=5
  19. sizeof=6

9.2.3 字符串函数:字符串函数strcmp

strcmp

  1. #include <stdio.h>
  2. #include <string.h>
  3. int mycmp(const char *s1, const char *s2)
  4. {
  5. // int idx = 0;
  6. // while(s1[idx]==s2[idx] && s1[idx] !='\0'){
  7. //// if(s1[idx] != s2[idx]){
  8. //// break;
  9. //// } else if(s1[idx]=='\0'){
  10. //// break;
  11. //// }
  12. // idx++;
  13. // }
  14. while(*s1==*s2 && *s1 != '\0'){
  15. s1++;
  16. s2++;
  17. }
  18. // return s1[idx]-s2[idx];
  19. return *s1 - *s2;
  20. }
  21. int main(int argc, char const *argv[])
  22. {
  23. char s1[] = "abc";
  24. char s2[] = "abc ";
  25. printf("%d\n", mycmp(s1,s2));
  26. printf("%d\n", 'a'-'A');
  27. return 0;
  28. }
  29. -32
  30. 32

9.2.4 字符串函数:字符串函数strcpy

strcpy

复制一个字符串

  1. #include <stdio.h>
  2. #include <string.h>
  3. char* mycpy(char* dst, const char* src)
  4. {
  5. // int idx = 0;
  6. // while (src[idx]){
  7. // dst[idx] = src[idx];
  8. // idx++;
  9. // }
  10. // dst[idx] = '\0';
  11. char* ret = dst;
  12. while(*dst++ = *src++)
  13. ;
  14. *dst = '\0';
  15. return ret;
  16. // return dst;
  17. }
  18. int main(int argc, char const *argv[])
  19. {
  20. char s1[] = "abc";
  21. char s2[] = "abc";
  22. mycpy(s1,s2);
  23. return 0;
  24. }

9.2.5 字符串函数:字符串函数strcat

strcat

安全问题

安全版本

9.2.6 字符串函数:字符串搜索函数

在字符串中找字符

  1. #include <stdio.h>
  2. #include <string.h>
  3. int main(int argc, char const *argv[])
  4. {
  5. char s[] = "hello";
  6. char *p = strchr(s, 'l');
  7. char c = *p;
  8. *p = '\0';
  9. // p = strchr(p+1, 'l');
  10. char *t = (char*)malloc(strlen(s)+1);
  11. strcpy(t,s);
  12. printf("%s\n", t);
  13. free(t);
  14. return 0;
  15. }
  16. he

字符串中找字符串

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注