C++标准库类型string

最近在学C++,看了《C++ Prime》的标准库类型string后,觉得应该总结下。

标准库类型string表示可变长的字符序列,使用string类型必须首先包含string头文件,string定义在命名空间std中。

一:定义和初始化string对象
string s1;           //默认初始化,s1是一个空串
string s2(s1);       //s2是s1的副本
string s2 = s1;      //等价于s2(s1)
string s3("value");  //s3是字面值"value"的副本,除了最后那个空字符外
string s3 = "value"; //等价于s3("value");
string s4(n,'c');     //把s4初始化为由连续n个字符c组成的串
                      //s4(5,'a') 等价于 s4 = "aaaaa"
 
二:string对象上的操作
os<<s        //将s写到输出流os当中,返回os
is>>s        //从is中读取字符串赋给s,
字符串以空白分隔,返回is
getline(is,s) //从is中读取一行赋给s,返回is
s.empty()     //为空返回true,否则返回false
s.size       //返回s中字符的个数
s[n]         //返回s中第n个字符的引用,位置n从0计起
s1+s2       //返回s1和s2连接后的结果
s1=s2       //用s2的副本代替s1中原来的值
s1==s2       //判断是否相等,对字母的大小写敏感
<,<=,>,>=  //比较2个string对象,对大小写敏感


下面详细了解下上面的部分操作
1.getline()函数
c++官网上的解释:
std::getline (string)
(1)istream& getline (istream& is, string& str, char delim);
(2)istream& getline (istream& is, string& str);
Get line from stream into string
Extracts characters from is and stores them into str until the delimitation character 
delim is found (or the newline character, '\n',for (2)).
The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.
If the delimiter is found, it is extracted and discarded (i.e. it is not stored and the next input operation will begin after it).
Note that any content in str before the call is replaced by the newly extracted sequence.
Each extracted character is appended to the string as if its member push_back was called.
从is中提取字符并将其存储到str直到分隔字符可以找到delim(对于第二个函数来说碰到'\n')。
如果文件的末尾到达了,或者在输入操作中发生了其他错误,提取也会停止。
如果发现分隔符,则提取并丢弃它(即它没有被存储,下一个输入操作将在它之后开始)。
注意,在调用之前的str中的任何内容都将被新提取的序列替换。
每个提取的字符被附加到字符串,就好像它的成员push_back被调用一样。

2.empty函数
std::string::empty
bool empty() const;
Test if string is empty
Returns whether the string is empty (i.e. whether its length is 0).
This function does not modify the value of the string in any way. To clear the content of a string, see string::clear.

3.size()函数
std::string::size
size_t size() const;
Return length of string
Returns the length of the string, in terms of bytes.
This is the number of actual bytes that conform the contents of the string, which is not necessarily equal to its storage capacity.
Note that string objects handle bytes without knowledge of the encoding that may eventually be used to encode the characters it contains.Therefore, the value returned may not correspond to the actual number of encoded characters in sequences of multi-byte or variable-lengthcharacters (such as UTF-8).
Both string::size and string::length are synonyms and return the same value.

4.字面值和string对象相加
string s1 = "hello"; string s2 = "world";
string s3 = s1 + ',' + s2 + '\n';
注意:当把string对象和字符字面值及字符串字面值混在一条语句中使用时,必须确保
每个加法

运算符的两侧的运算对象至少有一个是string:

string s2 = s1 + ',';   //正确:把一个string对象和一个字面值相加
string s3 = "hello" + ","; //错误:两个运算对象都不是string
string s5 = s4+","+"hello"; //正确:每个加法都有一个运算对象是string
string s7 = "hello"+","+s6; //错误:不能把字面值直接相加
string s5 = s4+","+"hello";这个可以看为 string s5 = (s4+",")+"hello";


三:下面是从C++官网拷贝的一些资料:
1.成员类型
member type
     definition
value_type
      char
traits_type
     char_traits<char>
allocator_type     allocator<char>
reference
      char&
const_reference
  const char&
pointer
          char*
const_pointer
 const char*
iterator
         a random access iterator to char (convertible to const_iterator)
const_iterator
  a random access iterator to const char
reverse_iterator
        reverse_iterator<iterator>
const_reverse_iterator
reverse_iterator<const_iterator>
difference_type
       ptrdiff_t
size_type
            size_t


2.成员函数
Iterators(迭代器):
begin       Return iterator to beginning (public member function )
end         Return iterator to end (public member function )
rbegin      Return reverse iterator to reverse beginning (public member function )
rend        Return reverse iterator to reverse end (public member function )
cbegin      Return const_iterator to beginning (public member function )
cend        Return const_iterator to end (public member function )
crbegin     Return const_reverse_iterator to reverse beginning (public member function )
crend       Return const_reverse_iterator to reverse end (public member function )


关于容量的函数:
size       Return length of string (public member function )
length     Return length of string (public member function )
max_size   Return maximum size of string (public member function )
resize     Resize string (public member function )
capacity   Return size of allocated storage (public member function )
reserve    Request a change in capacity (public member function )
clear      Clear string (public member function )
empty     Test if string is empty (public member function )   
shrink_to_fit   Shrink to fit (public member function )


元素访问:
operator[]    Get character of string (public member function )
at            Get character in string (public member function )
back          Access last character (public member function )
front         Access first character (public member function )


编辑相关函数:
operator+=    Append to string (public member function )
append        Append to string (public member function )
push_back     Append character to string (public member function )
assign        Assign content to string (public member function )
insert        Insert into string (public member function )
erase        Erase characters from string (public member function )
replace      Replace portion of string (public member function )
swap         Swap string values (public member function )
pop_back      Delete last character (public member function )


String operations:
c_str         Get C string equivalent (public member function )
data          Get string data (public member function )
get_allocator  Get allocator (public member function )
copy          Copy sequence of characters from string (public member function )
find          Find content in string (public member function )
rfind         Find last occurrence of content in string (public member function )
find_first_of  Find character in string (public member function )
find_last_of       Find character in string from the end (public member function )
find_first_not_of   Find absence of character in string (public member function )
find_last_not_of    Find non-matching character in string from the end (public member function )
substr             Generate substring (public member function )
compare            Compare strings (public member function )


Member constants
npos       Maximum value for size_t (public static member constant )


Non-member function overloads
operator+                 Concatenate strings (function )
relational operators        Relational operators for string (function )
swap                      Exchanges the values of two strings (function )
operator>>                Extract string from stream (function )
operator<<                Insert string into stream (function )
getline                    Get line from stream into string (function )


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值