C

  1. #include<stdio.h>
  2. #include<string.h>
  3. int main()
  4. {
  5. char words[] = "Hello,World";
  6. //代码等同于:char words[] = {'H', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', 0};
  7. printf("%s\n",words);//打印字符串
  8. printf("%d",strlen(words));//获取字符串的长度,需要引入string.h
  9. return 0;
  10. }

C++

采用C的方式

  1. #include <iostream>
  2. #include <cstring>
  3. int main()
  4. {
  5. //采用C的方式
  6. char words[] = "Hello,World";
  7. printf("%s\n",words);
  8. printf("%d\n", strlen(words));//获取字符串的长度,需要引入cstring
  9. return 0;
  10. }

采用string

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int main()
  5. {
  6. string s1("Hello");//需引入string及命名空间std
  7. cout << s1 << endl;
  8. string s2 = "n";
  9. cout << s2 << endl;
  10. string s3(8, 'x');
  11. cout << s3 << endl;
  12. cout << s1.size() << endl;//获取字符串长度
  13. return 0;
  14. }

输出结果:

Hello n xxxxxxxx 5

复制字符串

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int main()
  5. {
  6. string s1("Hello");
  7. string s2,s3;
  8. s2.assign(s1);//复制s1
  9. s3 = s1;//通过赋值实现复制s1(内存地址不会一样,仅拷贝内容)
  10. cout << s2 << endl;
  11. cout << s3 << endl;
  12. return 0;
  13. }

Hello Hello

截取字符串

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int main()
  5. {
  6. string s1("Hello");
  7. string s2,s3,s4;
  8. s2.assign(s1, 0, 2);//复制0位到2位
  9. s3 = s1[4];//复制单个字符
  10. s4 = s1.substr(2, 3);//从2位开始复制,长度为3
  11. cout << s2 << endl;
  12. cout << s3 << endl;
  13. cout << s4 << endl;
  14. return 0;
  15. }

He o llo

查找指定字符串

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int main()
  5. {
  6. string s1("Helloolleh");
  7. cout << "find:" <<s1.find("ll") << endl;//从前往后找,找不到返回string::npos
  8. cout << "rfind:" <<s1.rfind("e") << endl;//从后往前找,找不到返回string::npos
  9. if (s1.find("a") == string::npos){
  10. cout << "从字符串中找不到 a" << endl;
  11. }
  12. cout << s1.find("e",3) << endl;//从前往后找,从第三个字符开始查
  13. cout << s1.find_first_of("abe") << endl;
  14. //在s1中从前向后查找 “abcd” 中任何一个字符第一次出现的地方,如果找到,返回找到字母的位置
  15. //find_last_of() 从后找
  16. return 0;
  17. }

find:2 rfind:8 从字符串中找不到 a 8 1

删除字符串

  1. int main()
  2. {
  3. string s1("Helloolleh");
  4. cout << s1.erase(5) << endl;//第五位以后全部擦除
  5. cout << s1.erase(2,3) << endl;//删除2~3位的字符
  6. return 0;
  7. }

Hello He

替换/插入 字符串

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int main()
  5. {
  6. string s1("Hello");
  7. cout << s1.replace(1,2,"33333") << endl;//将s1中下标2 开始的3个字符换成“33333”
  8. string s2("Hello");
  9. string s3("World");
  10. cout << s2.replace(1,2,s3,2,2) << endl;
  11. //将s2中下标1开始的2个字符换成s3中下标2开始的2个字符
  12. string s4("Hello");
  13. cout << s4.insert(1,"33333") << endl;//将"33333"插入s4下标1的位置
  14. string s5("Hello");
  15. string s6("World");
  16. cout << s5.insert(1,s6,2,3) << endl;//将s6中下标2开始的3个字符插入s5下标1的位置
  17. return 0;
  18. }

H33333lo Hrllo H33333ello Hrldello