C++的string类

来源:互联网 发布:jsquery 数组加数据 编辑:程序博客网 时间:2024/06/02 04:02
/* 
** 注意iostream与iostream.h的区别
** 原来iostream是C++的头文件,iostream.h是C的头文件,
** 即标准的C++头文件没有.h扩展名
**
** iostream.h里面定义的所有类以及对象都是在全局空间里,
** 所以你可以直接用cout 但在iostream里面,
** 它所定义的东西都在名字空间std里面,
** 所以你必须加上using namespace std才能使用cout
*/
#include <iostream>  
/*
** <string>是c++ 的头文件,其内包含了一个string类,
** string s1就是建立一个string类的对象 
** <string.h> 的c语言的东西 并无类,所以不能 string s1 
** <cstring>文件实际上只是在一个命名空间std中include了 <string.h>,…
*/
#include <string>    //注意string与string.h的区别
using namespace std;


int main(void)
{
string str1("C++");
string str2("I Love");
string str3("You");
string str4;


// 字符串连接
str4 = str1;
cout << str4 << endl;


str4 = str2 + str1;
cout << str4 << endl;


// 字符串比较
if (str3 > str1) 
{
cout << "str3 > str1" << endl;
}
if (str3 == str1 + str2)
{
cout << "str3 == str1 + str2" << endl;
}


//使用null结束的字符串赋值
str1 = "This is a NULL-terminated string.";
cout << str1 << endl;


// 使用字符串对象构造另一个字符串
string str5(str1);
cout << str5 << endl;


//输入字符串
cout << "Enter a string: ";
cin >> str5;
cout << str5 << endl;
return 0;
}