本文目标
介绍 C++ 中的字符串。
标准库类型 string 表示可变长的字符序列,使用 string 类型必须首先包含string 头文件。作为标准的一部分,string 定义在 命名空间 std 中。
基本用法
- 计算长度 size(), length()
- 是否为空 empty()
- 字符串拼接(字符串相加) append(XXX);
- 在字符串中查找字符子串 find(XXX);
- 转为 const char*类型 c_str()
示例:
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 int main() 6 { 7 //// size, length, empty, append, find, c_str() 8 string str1; 9 string str2 = "Hello"; 10 string str3 = "Master "; 11 string str4 = "Oogway"; 12 char szStr5[30] = { 0 }; 13 sprintf(szStr5, "%s:%d", str4.c_str(), 1893977); 14 15 str1.append(str2); ///在字符串str1后面附加一个字符串(它是string类型) 16 str1 = str1 + " : " + str3; //// string 类型的对象,可以 通过 “+” 操作符将字符串连接起来。 17 str1 = "Demo--" + str1 ; ///这种写法也可以 18 str1.append(szStr5); /// 附加一个 char* 字符数组 19 20 int iLen1 = str1.size(); 21 int iLen2 = str1.length(); length()是 size()的别名,都是获取字符串长度. 22 if (str1.empty()) /// 判断字符串是否为空 23 { 24 cout << "str1 is empty." << endl; 25 } 26 int iPos = str1.find("Oogway"); /// 在字符串str1中查找 “Oogway”子串,返回子串第一次出现的位置。如果找不到,返回 -1.(至少在win32环境下测试,如果找不到是返回-1的) 27 28 cout << str1.c_str() << endl; /// str1是一个类的对象,不能直接输出; 29 system("pause"); 30 return 0; 31 }