1.字符串数组和字符串指针

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include <stdlib.h>
  4. int main(void)
  5. {
  6. char* s1 = "hello world";
  7. char s2[] = "hello world";
  8. //s1[2] = 'b'; //不可写
  9. s2[2] = 'b';
  10. printf("s1的地址是%p\r\n", s1);
  11. printf("s2的地址是%p\r\n", s2);
  12. system("pause");
  13. return 0;
  14. }

image.png

2.二维字符串数组的定义

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include <stdlib.h>
  4. int main(void)
  5. {
  6. char a[][10] = { "" }; //相当于a[0]--->char [10] 字符串长度小于10
  7. char *a[] = { "" }; //相当于a[0]--->char *
  8. system("pause");
  9. return 0;
  10. }

3.strlen/sizeof区别

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include <stdlib.h>
  4. int main()
  5. {
  6. char line[] = "asdasd";
  7. printf("strlen = %lu\n", strlen(line));
  8. printf("sizeof = %lu\n", sizeof(line));
  9. system("pause");
  10. return 0;
  11. }

image.png

4.strcmp

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include <stdlib.h>
  4. int main()
  5. {
  6. char* s1 = "Asd";
  7. char* s2 = "asd";
  8. if (strcmp(s1, s2) == 0)
  9. {
  10. printf("s1 = s2\n");
  11. }
  12. else
  13. {
  14. printf("%d\n", strcmp(s1, s2));
  15. }
  16. system("pause");
  17. return 0;
  18. }

image.png

5.strcpy

复制字符串

  1. #pragma warning(disable:4996)
  2. #include<stdio.h>
  3. #include<string.h>
  4. #include <stdlib.h>
  5. int main()
  6. {
  7. char s1[] = "Asd";
  8. char *s2 = (char *)malloc(strlen(s1) + 1);
  9. strncpy(s2, s1,4);//安全一些只能拷贝strlen(s1) + 1个字符
  10. printf("s2 = %s",s2);
  11. system("pause");
  12. return 0;
  13. }

6.strchr/strsht

  1. char s1[] = "hello";
  2. char *p = strchr(s1,'l');
  3. 输出
  4. "llo"