标准库类型 String

本文详细介绍了C++标准库中的String类型,包括定义和初始化方法、String对象的基本操作,如find族函数、其他字符串函数,以及如何处理string中的字符。文章强调了处理string时的注意事项,如size()函数返回值的类型问题和字符串加法的顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

标准库类型 String

定义和初始化String对象
string test1;           //空串
string test2 = "内容";  //使用=
string test3("内容");   //使用引用字符数组作为参数传给构造函数
string test4(test2);   //用一个string初始化另一个string
string test4_1(test2,pos)//从test2中的第pos个位置开始,拷贝所有剩余字符
string test5(test2,pos,num); //从test2中的第pos个位置开始,拷贝个数为num个字符
string test6 = test2 + "内容" + test3 //混合初始化
string test7 = test2.substr(pos,num); //从test2中的第pos个位置开始,拷贝个数为num个字符
string test8 = test2.substr(); //参数列表为空则会拷贝test2的整个对象(复制test2的简便方法)
string test9(num,char); //拷贝num个字符型char到test9
  1. 当我们用一个指向c风格字符串的指针(或者字符数组)创建string时,该字符串必须以‘\0’结尾,拷贝操作遇到空字符时停止。如果我们还传递给构造函数一个计数值,数组就不必以空字符结尾。
  2. 如果我们未传递计数值且数组也未以空字符结尾,或者给定计数值大于数组大小,则构造数组的行为是未定义的
String对象上的简单操作
在String标准库中的基本操作
名称操作
os<<s将s写出到输出流os中,返回os
is>>s从输入流is读入字符户赋值给s,字符串以空白分格,返回is。会自动忽略空格
getline(is,s)从is中读入一行赋给s,返回is
s.empty()s为空则返回ture,否则返回false
s.size( )返回s中字符的个数
s[n]返回s中第n个字符的引用,n从0开始
s1+s2返回s1和s2连接后的结果
s1=s2用s2的副本代替s1中原来的字符
s1==s2如果s1与s2中的字符完全一样,则返回true,对大小写敏感
s1!=s2与上相反
<,<=,>,>=字符串的比较,对大小写敏感
getline函数
//以下是string标准库函数,直接用即可(getline(...))
istream& getline (istream& is, string& str);
istream& getline (istream& is, string& str, char delim);
// is是输入流,一般为cin
// str是目标string
// delim 是结束字符:遇到该字符时停止输入,该结束字符不输入,并且也不停留在键盘缓冲区,而是被抛弃
//以下是iostream 标准库函数,使用形式为cin.getline(...)
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
//不能使用在string类型中,只能使用为字符数组

其返回值是cin流输入的状态,如没有异常或者不输入EOF将会一直读入

String标准库中的find族函数
find()
size_t find (const string& str, size_t pos = 0) const;    //string
size_t find (const char* s, size_t pos = 0) const;        //c-string
size_t find (const char* s, size_t pos, size_t n) const;  //buffer 
size_t find (char c, size_t pos = 0) const;               //character
//pos:可以缺省不要这个参数,也可以写作0,从pos位置开始搜索
//n:表示查找对象是模式字符串的前n个字符
  • Find occurrence of content in string
  • When pos is specified, the search only includes characters at or after position pos, ignoring any possible occurrences before that character. And when pos is neglected, it functions as 0.

rfind()
size_t rfind (const string& str, size_t pos = npos) const;    //string 
size_t rfind (const char* s, size_t pos = npos) const;        //c-string
size_t rfind (const char* s, size_t pos, size_t n) const;     //buffer
size_t rfind (char c, size_t pos = npos) const;               //character
  • Find last occurrence of content in string
  • When pos is specified, the search only includes characters at or before position pos, ignoring any possible occurrences after pos.

find_first_of:
size_t find_first_of (const string& str, size_t pos = 0) const;      //string	
size_t find_first_of (const char* s, size_t pos = 0) const;          //c-string
size_t find_first_of (const char* s, size_t pos, size_t n) const;    //buffer 
size_t find_first_of (char c, size_t pos = 0) const;                 //character
//n:表示s中的前n个字符是有效范围,查找string中第一次出现这前n个字符的位置
  • Find character in string
  • Notice that it is enough for one single character of the sequence to match (not all of them).

  • When pos is specified, the search only includes characters at or after position pos, ignoring any possible occurrences before that character.

find_first_not_of()
size_t find_first_not_of (const string& str, size_t pos = 0) const;      //string	
size_t find_first_not_of (const char* s, size_t pos = 0) const;          //c-string
size_t find_first_not_of (const char* s, size_t pos, size_t n) const;    //buffer 
size_t find_first_not_of (char c, size_t pos = 0) const;                 //character
  • Find absence of character in string
  • Searches the string for the first character that does not match any of the characters specified in its arguments str.

  • When pos is specified, the search only includes characters at or after position pos, ignoring any possible occurrences before that character.

find_last_of()
size_t find_last_of (const string& str, size_t pos = 0) const;      //string	
size_t find_last_of (const char* s, size_t pos = 0) const;          //c-string
size_t find_last_of (const char* s, size_t pos, size_t n) const;    //buffer 
size_t find_last_of (char c, size_t pos = 0) const;                 //character
  • Find character in string from the end
  • Searches the string for the last character that matches any of the characters specified in its arguments.

  • When pos is specified, the search only includes characters at or before position pos, ignoring any possible occurrences after pos.

find_last_not_of
size_t find_last_not_of( const basic_string& str, size_t pos = npos )    //string	
size_t find_last_not_of( const CharT* s, size_t pos = npos ) 		  	 //c-string
size_t find_last_not_of( const CharT* s, size_t pos, size_t count ) 	 //buffer 
size_t find_last_not_of( char ch, size_t pos = npos )					 //character
  • Finds the last character equal to none of the characters in the given character sequence.
  • The search considers only the interval [0, pos]. If the character is not present in the interval, npos will be returned. The auto pos, if neglectied, is considered npos, namely the last character.
  • buffer :Finds the last character equal to none of characters in the range [s, s+count). This range can include null characters.
  • the function returns where it matches, the location is quantified from the begining of the string
String标准库中的其他函数
replace()
string& replace (size_t pos,  size_t len,  const string& str);      //string
string& replace (iterator i1, iterator i2, const string& str);      //string

string& replace (size_t pos,  size_t len,  const string& str,
                 size_t subpos, size_t sublen);                     //substring

string& replace (size_t pos,  size_t len,  const char* s);          //c-string
string& replace (iterator i1, iterator i2, const char* s);          //c-string

string& replace (size_t pos,  size_t len,  const char* s, size_t n);//buffer
string& replace (iterator i1, iterator i2, const char* s, size_t n);//buffer

string& replace (size_t pos,  size_t len,  size_t n, char c);       //fill
string& replace (iterator i1, iterator i2, size_t n, char c);       //fill
  • Replaces the portion of the string that begins at character pos and spans len characters (or the part of the string in the range between [i1,i2)) by new contents, it is like remove some part of the string, and then and some gredients into the place where charactors were removed. The string’s length is not a point to considerate, for that the length or space is automaticly changed

  • What to Copy
    • substring: Copies the portion of str that begins at the character position subpos and spans sublen characters (or until the end of str, if either str is too short or if sublen is string::npos).
      • And if len> sublen, this part of s will also be replaced, and the other added;
    • buffer: Copies the first n characters from the array of characters pointed by s.
    • fill: Replaces the portion of the string by n consecutive copies of character c.
    • initializer list: Copies each of the characters in il, in the same order.
  • Parameters

    • pos:Position of the first character to be replaced. If this is greater than the string length, it throws out_of_range.

    • len:Number of characters to replace (if the string is shorter, as many characters as possible are replaced). A value of npos indicates all characters until the end of the string, for that npos is actually really a large num

    • subpos:Position of the first character in str that is copied to the object as replacement. If this is greater than str’s length, it throws out_of_range.

    • sublen:Length of the substring to be copied (if the string is shorter, as many characters as possible are copied). A value of string::npos indicates all characters until the end of str.

    • c:Character value, repeated n times.

insert()
s.insert(loc,num,c)//在loc位置之前插入num个字符c
s.erase(loc,num);    //从loc位置开始删除num个字符
处理string中的字符
基本操作函数
函数
isalnum(c)c为数字或者字母时为真
isalpha(c)c为字母时为真
iscntrl(c)c为控制字符时为真
isdigit(c)c为数字时为真
isgraph(c)c不是空格并且可以打印时为真
islower(c)c是小写字母时为真
isprint(c)c可以打印,即c是空格或者可视字符时为真
ispunct(c)c是标点符号时为真(即c不是控制字符、字母、数字、可打印空白)
isspace(c)c时空白时为真(c为空格、横向制表符、纵向制表符、回车符、换行符等)
isupper(c)c时大写字母时为真
isxdigit(c)c是十六进制数字时为真
tolower(c)把大写字母(如果是的话)转换成小写字母,返回小写字母
toupper(c)与上相反
使用基于范围的for语句处理string对象中的每个字符
for(declaration:expression)
{
	statement;
}
/*
declaration:定义一个变量,该变量用于访问序列中的基础元素
expression:一个对象,内含一个序列
每次迭代,declaration部分的变量会被自动化初始化为expression部分的下一个元素值
*/
//example:
string str("some string");
for(auto c:str)//using "auto" to have the compiler decide its type.
	cout<<c<<endl;
  • 使用范围for语句改变字符串中的字符:循环变量必须被定义为引用类型for(auto &c : s ),这样这个循环变量相当于被以此绑定到了序列的每一个元素上,籍此修改序列中的字符

  • 只处理一部分字符

    • 使用下标。下标运算符[]接收的是unsigned int类型的值,这个值表示要访问的字符的位置,返回值是该位置上字符的引用,从0开始计数。

    • 使用超出s.size()-1的值将会引起未知错误,故而使用下标访问空string将会导致错误,应该使用如下结构

      if(!s.empty())
          cout<<s[0]<<endl;
      
    • 使用下标进行迭代-就是用for循环,切记保持下标引用的合法性
    string a("hello there");
    for (decltype(a.size())index = 0; index != a.size() && !isspace(a[index]); ++index)
    {
    	a[index] = toupper(a[index]);
    }
    
常见注意事项
s.size()的类型
  • s.size( )函数返回的值是一个无符号整数类型,用它和带符号整数类型进行混合运算可能发生诸多错误,不要直接在表达式中对其产生的值进行运算、判断,而是先用一个int类型记录这些值,再进行运算、输出、判断。在普通的for循环中我们大多可以这么使用,但是如果出现size()-1这种式子,请一定注意将它转换为int类型!使用int(size()-1),否则一旦size()小于等于1,将引发灾难性的错误
string对象之间的加法
  • a + b 表示把b接到a的后面,注意加法的顺序。

  • 当把string对象和字符字面值对象混在一条加法语句中使用时,确保每个加法运算符的两次的运算对象都至少有一个是string对象。注意括号以及连贯性

    string s4 = s1 +", ";//合法
    string s5 = "hello" + ", ";//不合法
    string s6 = s1 + "," + " world";//合法:从左到右读即可发现符合条件
    string s7 = "hello" + ", "+ s2;//不合法
    string s8 = "hello" + s2;//合法,并且输出为“hello+*s2"
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值