您的位置:首页 > 其它

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

2011-08-08 22:28 288 查看
在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;
}


 

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