C++的字符串变量

1. string的定义和初始化

  1. string str;
  2. string str = "hello";
  3. str = "world";

2. string的用法

  • 字符串拷贝: =
  • 字符串比较
    • 大于: >
    • 小于: <
    • 等于: ==
    • 不等于: !=
  • 字符串的连接: + +=
  • 获取字符串中某个字符: []

    3. 示例

    ```cpp

    include

    include //

    include

    using namespace std;

int main(int argc, char const *argv[]) { cout << “————-c 风格字符串” << endl; char str1[36] = “hello”; char str2[36] = “world”; if(strcmp(str1, str2) < 0){ cout << “small str: “ << str1 << endl; }else{ cout << “small str: “ << str2 << endl; }

  1. char str3[36] = {0};
  2. strcpy(str3, str1);
  3. cout << "str3 : " << str3 << endl;
  4. strcat(str1, str2);
  5. cout << "str1 : " << str1 << endl;
  6. cout << "str1[4] : " << str1[4] << endl;
  7. cout << "----------c++ 风格字符串" << endl;
  8. string str11 = "hello";
  9. string str12 = "world";
  10. if(str11 < str12){
  11. cout << "small str : " << str11 << endl;
  12. }else{
  13. cout << "small str : " << str12 << endl;
  14. }
  15. string str13;
  16. str13 = str11;
  17. cout << "str13 : " << str13 << endl;
  18. //str11 += str12;
  19. str11 = str11 + str12;
  20. cout << "str11 : " << str11 << endl;
  21. cout << "str11[4] : " << str11[4] << endl;
  22. return 0;

} ```