字符串变量

image.png

字符串常量

image.png

字符表示说明

image.png

Unicode编码

image.png

字符串的指针表示

image.png
image.png

  1. # include <string.h>
  2. #include <iostream>
  3. using namespace std;
  4. int main()
  5. {
  6. // 定义一个数组
  7. char strHelloWorld[11] = { "helloworld" }; // 这个定义可以
  8. char* pStrHelloWrold = "helloworld";
  9. pStrHelloWrold = strHelloWorld;
  10. //strHelloWorld = pStrHelloWrold; // 数组变量的值不允许改变
  11. // 字符0, '\0', '0'的区别
  12. //char c1 = 0;
  13. //char c2 = '\0';
  14. //char c3 = '0';
  15. // 通过数组变量遍历修改数组中的元素值
  16. for (int index = 0; index < strlen(strHelloWorld); ++index)
  17. {
  18. strHelloWorld[index] += 1;
  19. std::cout << strHelloWorld[index] << std::endl;
  20. }
  21. // 通过指针变量遍历修改数组中的元素值
  22. for (int index = 0; index < strlen(strHelloWorld); ++index)
  23. {
  24. pStrHelloWrold[index] += 1;
  25. std::cout << pStrHelloWrold[index] << std::endl;
  26. }
  27. cout << endl; // 换行
  28. // 计算字符串长度
  29. cout << "字符串长度为: " << strlen(strHelloWorld) << endl;
  30. cout << "字符串占用空间为: " << sizeof(strHelloWorld) << endl;
  31. return 0;
  32. }

字符串的常见操作

image.png
image.png
image.png

  1. #include <string.h> //使用C库的头文件
  2. #include <iostream>
  3. using namespace std;
  4. const unsigned int MAX_LEN_NUM = 16;
  5. const unsigned int STR_LEN_NUM = 7;
  6. const unsigned int NUM_TO_COPY = 2;
  7. int main()
  8. {
  9. char strHelloWorld1[ ] = { "hello" };
  10. char strHelloWorld2[STR_LEN_NUM] = { "world1" };
  11. char strHelloWorld3[MAX_LEN_NUM] = {0};
  12. //strcpy(strHelloWorld3, strHelloWorld1); // hello
  13. strcpy_s(strHelloWorld3, MAX_LEN_NUM, strHelloWorld1);
  14. //strncpy(strHelloWorld3, strHelloWorld2, NUM_TO_COPY); // wollo
  15. strncpy_s(strHelloWorld3, MAX_LEN_NUM, strHelloWorld2, NUM_TO_COPY);
  16. //strcat(strHelloWorld3, strHelloWorld2); // wolloworld1
  17. strcat_s(strHelloWorld3, MAX_LEN_NUM, strHelloWorld2);
  18. //unsigned int len = strlen(strHelloWorld3);
  19. unsigned int len = strnlen_s(strHelloWorld3, MAX_LEN_NUM);
  20. for (unsigned int index = 0; index < len; ++index)
  21. {
  22. cout << strHelloWorld3[index] << " ";
  23. }
  24. cout << endl;
  25. // 小心缓冲区溢出
  26. //strcat(strHelloWorld2, "Welcome to C++");
  27. strcat_s(strHelloWorld2, STR_LEN_NUM, "Welcome to C++");
  28. return 0;
  29. }

字符串操作中存在的问题

image.png

string简介

image.png
image.png
image.png
image.png
image.png
image.png