2007年8月26日星期日

string container

1 string 使用

其实,string并不是一个单独的容器,只是basic_string 模板类的一个typedef 而已.
string 其实相当于一个保存字符的序列容器,因此除了有字符串的一些常用操作以外,还有包含了所有的序列容器的操作。字符串的常用操作包括:增加、删除、修改、查找比较、链接、输入、输出等。详细函数列表参看附录。不要害怕这么多函数,其实有许多是序列容器带有的,平时不一定用的上。

1.1 operators


string 重载了许多操作符,包括 +, +=, <, =, , [], <<, >>等,正式这些操作符,对字符串操作非常方便.有了这些操作符,在STL中仿函数都可以直接使用string作为参数,例如 less, great, equal_to 等,因此在把string作为参数传递的时候,它的使用和int 或者float等已经没有什么区别了.


1.2 眼花缭乱的string find 函数


find
查找
rfind
反向查找
find_first_of
查找包含子串中的任何字符,返回第一个位置
find_first_not_of
查找不包含子串中的任何字符,返回第一个位置
find_last_of
查找包含子串中的任何字符,返回最后一个位置
find_last_not_of
查找不包含子串中的任何字符,返回最后一个位置


1.3 string insert, replace, erase


string只是提供了按照位置和区间的replace函数,而不能用一个string字串来替换指定string中的另一个字串。这里写一个函数来实现这个功能:
void string_replace(string & strBig, const string & strsrc, const string &strdst)
{
string::size_type pos=0;
string::size_type srclen=strsrc.size();
string::size_type dstlen=strdst.size();
while( (pos=strBig.find(strsrc, pos)) != string::npos)

{
strBig.replace(pos, srclen, strdst);
pos += dstlen;
}
}

Tips: A handy way of putput string

...

vector::iterator it = unique(strVec.begin(), strVec.end());

(strVec.begin(), it, ostream_iterator(cout, "\n"));


2 string 和 C风格字符串
const charT* c_str() const
//c_str ()returns a char[] with '\0' in its end.
const charT* data() const
//data() returns a char[] without '\0' in its end
size_type copy(charT* buf, size_type n, size_type pos = 0) const
//copy() the contents of string into buffer.

Accesory for functions in string container

begin
得到指向字符串开头的Iterator
end
得到指向字符串结尾的Iterator
rbegin
得到指向反向字符串开头的Iterator
rend
得到指向反向字符串结尾的Iterator
size
得到字符串的大小
length
和size函数功能相同
max_size
字符串可能的最大大小
capacity
在不重新分配内存的情况下,字符串可能的大小
empty
判断是否为空
operator[]
取第几个元素,相当于数组
c_str
取得C风格的const char* 字符串
data
取得字符串内容地址
operator=
赋值操作符
reserve
预留空间
swap
交换函数
insert
插入字符
append
追加字符
push_back
追加字符
operator+=
+= 操作符
erase
删除字符串
clear
清空字符容器中所有内容
resize
重新分配空间
assign
和赋值操作符一样
replace
替代
copy
字符串到空间
find
查找
rfind
反向查找
find_first_of
查找包含子串中的任何字符,返回第一个位置
find_first_not_of
查找不包含子串中的任何字符,返回第一个位置
find_last_of
查找包含子串中的任何字符,返回最后一个位置
find_last_not_of
查找不包含子串中的任何字符,返回最后一个位置
substr
得到字串
compare
比较字符串
operator+
字符串链接
operator==
判断是否相等
operator!=
判断是否不等于
operator< 判断是否小于 operator>>
从输入流中读入字符串
operator<<
字符串写入输出流

没有评论: