您的位置:首页 > 编程语言 > C语言/C++

C++ string(初始化和部分函数的使用)

2017-05-10 20:33 190 查看
#include<string>
#include<stdlib.h>
#include<stdio.h>
#include<iostream>
using namespace std;

int main()
{
//string 初始化
string s1 = "ywb";
string s2(s1);
string s3 = s2;
string s4("yangwen");
string s5(10, 'c');
cout << s1 << " " << s2 << " " << s3 << " " << s4 << " " << s5 << endl;

//string 一部分函数的使用
string str("yangwenbin");
int length = str.length();//求取字符串长度
int length1 = str.size(); //求取字符串长度
cout << length << " " << length1 << endl;
for (int i = 0; i < length1; i++)
{
cout << str.at(i) << " " ;  //返回字符串第i个位置的字符
}
cout << endl;
cout << *str.begin() << endl;   //返回字符串的首字符
cout << *(str.end() - 1) << endl;; //返回字符串的尾元素
if (!str.empty())  //判断字符串是否为空
{
cout << "i am not empty" << endl;;
}
str.resize(length + 10, 'a'); //重新分配空间,将多余的十个空间分配a
cout << str << endl;;
str.clear(); //清除字符串

if (str.empty())  //判断字符串是否为空
{
cout << "i am empty" << endl;;
}
str.append("ywb");
cout << str << endl;
str.append(" hell0");//append 在string后插入字符串
cout << str;
system("pause");
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: