string: C++的字符串类型

标准库string类//include
string表示可变长度的字符序列
字符串是对象
string类支持字符串对象的各种操作
各种初始化方式.
字符串之间的复制、比较、连接.
查询字符串长度和判断字符串是否为空.
访问字符串中的单个字符.
string的简单使用
#include <iostream> #include <string> using namespace std; int main() {string s1, s2;//创建两个空字符串对象 string s3 = "Hello, world!"; //创建s3, 并初始化 string s4("I am ") ; s2 = "Today" ;//赋值 s1=s3+" "+s4;//字符串连接 s1+="5";//术尾追加 cout << s1 + s2 + "!”<<endl; //输出字符串内容
string的常用操作
STL的简单应用1
读写string对象时应用C++表示方法
即 string s;
cin>>s;
cout<<s;
同时可以用循环语句来读写string的对象
string word;
while(cin>>word)
cout<<word;
写string时不能包含有空格的语句
为了弥补这一缺陷 我们可以用getline() 函数(以回车为结束标志)
此函数包括两个参数,分别为输入流对象(一般为cin)和存放读入字符串的string对象
string line;
while (getline (cin, line))
cout<<line<<endl;

  • string还可以判断字符串是否为空以及判断其长短
    eg :string line;
    line. empty () ;
    line. size() ;

-同时还可以用来比较大小
依照字典顺序定义并区分大小写字母。
string s1=“hello”;
string s2=“hello world”;//s2>s1
string s3=“Hello”;//s3<s2,s3<s1

相关文章:

  • 2021-07-15
  • 2022-01-23
  • 2022-01-12
  • 2022-01-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-02
  • 2021-12-22
猜你喜欢
  • 2021-06-03
  • 2022-02-07
  • 2021-06-26
  • 2021-10-08
  • 2021-07-25
  • 2021-06-20
  • 2021-10-31
相关资源
相似解决方案