STL------string的简单使用

在C语言中我们用char的结构体来定义一个数组,如char s[50];但是char数组定义之后,数组大小就不能改变了,在C++ STL中提供了一个方便的string类型来表示字符串,且string的长度是可变的。
string类型常用函数:
1.构造函数
2.size函数返回字符串大小
3.compare函数比较字符串
4.insert函数可在任意位置插入数据
5.append函数字符串的连接、尾部追加
6.push_back函数在尾部添加字符
7.empty函数判断字符串是否为空
8.find函数在字符串中查找
9.substr函数求子字符串
10.erase函数擦除指定的字符
11.replace函数替换字符
12.begin函数返回指向字符串首部的迭代器指针
13.end函数返回指向字符串尾部的迭代器指针(即'\0')
14.getline函数读入一行字符串(和cin的getline函数不同)
15.c_str函数将string转换成char*(通过strcpy赋值)

 

字符串的输入输出

//ioput.cc
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s1("Hello World...");
    cout << s1 << endl;

    string s2 = s1;
    cout << s2 << endl;

    string s3;
    cout << "please enter a string:";
    cin >> s3;
    cout << s3 << endl;
}

值得注意的是:当要求输入字符串s3时,输入时不要出现空格,否则字符串会被截断。如输入Hello World则输出的s3为Hello

 

find函数和substr函数的结合使用

//getstr.cc
#include <iostream>
#include <string>
using namespace std;

int main()
{
    //找出子字符串index.html
    string s("GET /index.html HTTP/1.1");
    string::size_type start = s.find(" ", 0);
    string::size_type end = s.find(" ", start + 1);
    string s1 = s.substr(start + 2, end - start - 1);
    cout << s1 << endl;

    return 0;
}


begin和end函数的使用

//useiterator.cc
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s("www.sina.com.cn");
    string::iterator itr1 = s.begin();
    string::iterator itr2 = s.end();

    for(string::iterator itr = itr1; itr < itr2; itr++)
    {
        cout << *itr << endl;
    }

    return 0;
}


 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值