在C语言中,char的用处很多单操作繁琐,大多数以函数形式操作。C++中,增加了string类型。
#include<iostream>
#include<string>
using namespace std;
int main()
{
string name = "xiaoming";
string hobby("basketball");
cout << name << " " << hobby << endl;
system("pause");//暂停程序
return 0;
}
以下是string的初始化操作。
string的一些常用操作。
一段示例代码:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string name;//用户名
cout << "Please input your name" << endl;
getline(cin, name);//如果直接用cin,那么回车会被保存,getline能将输入储存在name中
if (name.empty())
{
cout << "input is null.." << endl;
system("pause");//暂停程序
return 0;
}
if (name=="imooc")
{
cout << "You are a adminitrator" << endl;
}
cout << "hello" + name << endl;
cout << "your name length is" <<name.size() << endl;
cout << "your name first letter is" << name[0] << endl;
system("pause");//暂停程序
return 0;
}