- C99 有很多和 string 相关的函数,
如 strcat , strchr , strcmp , strcpy , strlen , strncat , strncmp , strncpy 等。
然而使用 C++(www.cppentry.com) 编程(www.cppentry.com)时,所有和 string 相关的操作均可以使用 string 类的相关接口完成, string 提供和原来 C 接口类似的
功能和性能,同时提供更高的安全性。
-
- String 类
有一个特
性: a string of length n must manage a block of memory whose size is at least n + 1 。
即长度为 n 的 string 对象,其内存空间至少为 n+1 个字符,且最后一个字符为 ’\0’ 。
-
- 不过在进行 string 操作时,有一点必须牢记: C/C++(www.cppentry.com) 语言的 string 是以 ’\0’ 结尾的,对不以 ’\0’ 结尾的 string 进行操作容易引发错误,甚至导致内存溢出等 crash 。
-
- C++(www.cppentry.com) 的 string 类,除了用于处理常规 string 操作 外,其本身也可用于存储各种数据 ,如文件数据,此时并不要求 string 对象必须以 ’\0’ 结尾。使用者采用 string( const char* str, size_type length ); 来封装特定长度的 char* 数据块。 String 类的各种运算符将保证数据传递的完整性,即 string 对象。
-
- 示例:
-
- view sourceprint
- 01 #include <iostream>
-
- 02 using namespace std;
-
- 03
-
- 04 int main() {
-
- 05 std::string str("test string");
-
- 06 cout<<str<<" "<<str.c_str()<<endl;
-
- 07 cout<<str.size()<<endl;
-
- 08
-
- 09 char* buf = new char[str.size()+1];
-
- 10 memset(buf, 0, sizeof(buf));
-
- 11
-
- 12 string test(buf, str.size()); // 封装非字符数据
-
- 13 cout<<test<<" "<<test.c_str()<<endl;
-
- 14 cout<<test.size()<<endl;
-
- 15
-
- 16 memcpy(buf, str.c_str(), str.size());
-
- 17
-
- 18 test = string(buf, str.size()); // 封装字符数据,并自动加上 ’\0’ 结束符
-
- 19 cout<<test<<" "<<test.c_str()<<endl;
-
- 20 cout<<test.size()<<endl;
-
- 21
-
- 22 return 0;
-
- 23 }
- 其输出:
-
- test string test string
-
- 11
-
-
-
- 11
-
- test string test string
-
- 11
-
- 说明:这个例子说明:当使用 string( const char* str, size_type length ); 来构造string对象时,string对象的长度由外部指定,数据则来自 str ,如果 length 大于 str 地址范围,可能引发 crash!
-
- 这个例子也说明了 string 可用于封装数据,即使是 ’\0’ 的数据。因此,string类可以用于存储各种数据,字符串、非字符串 (图片,视频)等数据。
-
- 注
意:将数据拷贝到内存时,不要使用strcpy, 应该使用memcpy,因为strcpy、strncpy碰到 ’\0’ 将认为拷贝结束。 总之,不
要使用和str*** 相关的函数去操作内存数据,除非数据只能是string(memcpy完全可拷贝任何数据) 。
|