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赋值)
字符串的输入输出
值得注意的是:当要求输入字符串s3时,输入时不要出现空格,否则字符串会被截断。如输入Hello World则输出的s3为Hello
find函数和substr函数的结合使用
begin和end函数的使用
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; }
相关文章推荐
- 一个使用STL::string时遇到的诡异bug
- lr_eval_string()函数以及LR中参数、变量的简单使用
- String简单使用
- String字符串使用方法简单测试
- (转)标准模板库(STL)的 std::string 与Unicode的使用
- string的简单使用
- lr_eval_string()函数以及LR中参数、变量的简单使用
- [Zlib]_[初级]_[使用zlib库压缩和解压STL string]
- STL中的容器使用比较(string vector list deque set map)
- C#中BitConverter.ToUInt16()和BitConverter.ToString()的简单使用
- STL String的使用[转]
- Android的string-array数据源简单使用
- linux c++ stl hash_map basic_string 使用
- C++ 中的string的简单使用 (续)
- stl.string使用总结
- String-lastIndexOf()、replace()简单使用
- STL string,vector,complex,limits类的使用
- STL第一章-string的使用方法
- lr_eval_string()函数以及LR中参数、变量的简单使用
- Android的string-array数据源简单使用