本次测试是在多字节环境下进行测试。
在C++中则把字符串封装成了一种数据类型string,可以直接声明变量并进行赋值等字符串操作
#include <iostream>
using namespace std;
void main()
{
string my_string;
}
用户不用包含任何头文件,仅仅使用std命名空间即可使用string类型,上述例子中,如果将using namespace std;注释,则string类型提示未定义。
若头文件引用了<string>,但是没有使用std命名空间,还是无法正常使用string,此处说明string类是定义在std中,通过网上资料查询,可以这样认为:string类是“C++ Standard Library (C++标准库)的一部分”,所以在使用string时需要使用命名空间std,或者可以直接std::string 的方式使用。
此处有个疑点,c++中string string.h cstring 头文件的意义是什么:
可以查看博主:https://blog.youkuaiyun.com/luoweifu/article/details/20242307 的内容。
对于VC++,由于微软做了一些变通,所有无扩展名的头文件均可以用带.h扩展名的代替。 来源:https://zhidao.baidu.com/question/31579802.html
对c++中的字符串可以从两个方面理解,一种是c方式的字符串,就是定义char*p_char类型,一种是string类型的,就是定义string s_ser;
对于char*类型的处理,在上篇博客https://blog.youkuaiyun.com/mmdsb/article/details/80242148 中做了简单介绍,下面着重讲一下string类型的字符串操作。
#include <iostream>
#include <string>
using namespace std;
void main()
{
printf("%d\n", strlen("abc"));//可以使用c中所有字符串的操作
string my_string = "test string in c plus plus!";
//cout << "string length" << strlen(my_string) << endl;//出错,因为strlen的入参是char*
cout << "string length " << my_string.length() << endl;//27
cout << "string length " << sizeof(my_string) << endl;//28,会把最后的结束符‘\0’统计
cout << my_string << endl;//当不使用头文件<string>时,会报错:二进制“ << ”: 没有找到接受“std::string”类型的右操作数的运算符(或没有可接受的转换
my_string = "hello!";
cout << "string " << my_string << " length " << my_string.length() << endl;
cout << my_string[1] << endl;//e
my_string[1] = 'a';
cout << my_string<< endl;//hallo!
}
通过上述例子可以看到,c++中的string类,集成了c中char* p_char 和char cchar[] 类型字符串的赋值方法:既可以通过字符串进行赋值,又可以使用'*'字符单独改变其中某一个位置的字符值。
另外c++中的字符串有一些自己特有的操作方法,详细请看下面博客中内容: