std::basic_string::copy
size_type copy(CharT*dest, size_type count,size_type pos=0);
Copies a substring[pos, pos+count)to character string pointed to bydest. If the requested substring lasts past the end of the string, or ifcount==npos, the copied substring is[pos, size()). The resulting character string is not null-terminated.
Ifpos>=size(),std::out_of_rangeis thrown.
Parameters
destpointer to the destination character string
posposition of the first character to include
countlength of the substring
Return value
number of characters copied
example
1 #include <string>
2 #include <iostream>
3
4 using namespace std;
5
6 int main ()
7 {
8 size_t length;
9 char buffer[8];
10 string str("Test string......");
11
12 length=str.copy(buffer,7,6); //从buffer6,往后数7个,相当于[ buffer[6], buffer[6+7] )
13 buffer[length]='\0'; //加上'\0'使得buffer就到buffer[length]为止;
14
15 cout <<"buffer contains: " << buffer <<endl;
16
17 length=str.copy(buffer,str.size(),6); //从buffer6,往后数7个,
18 //相当于[ buffer[6], buffer[6+7] )
19 buffer[length]='\0'; //使得buffer就到buffer[length]为止;
20 cout <<"buffer contains: " << buffer <<endl;
21
22 length=str.copy(buffer,7,0); //相当于[ buffer[0], buffer[7] )
23 buffer[length]='\0';
24
25 cout << "buffer contains: " << buffer <<endl;
26
27 length=str.copy(buffer,7); //缺省参数pos,默认pos=0;
28 //相当于[ buffer[0], buffer[7] )
29 buffer[length]='\0';
30 cout << "buffer contains: " << buffer <<endl;
31 length=str.copy(buffer,string::npos,6); //相当于[ buffer[7], buffer[npos] )
32 //buffer越界赋值,没有出错
33 buffer[length]='\0';
34 cout<<string::npos<<endl; //string::npos是4294967295
35 cout<<buffer[string::npos]<<endl; //实际是越界访问,但没有出错,输出空
36 cout<<buffer[length-1]<<endl; //实际是越界访问,但没有出错,输出了其他字符
37 cout << "buffer contains: " << buffer <<endl;
38 length=str.copy(buffer,string::npos); //相当于[ buffer[0], buffer[npos] )
39 //buffer越界赋值,没有出错
40 buffer[length]='\0';
41 cout << "buffer contains: " << buffer <<endl; //buffer越界
42 cout<<buffer[string::npos]<<endl; //越界访问,输出空
43 cout<<buffer[length-1]<<endl; //越界访问,没有输出str最后一个字符,输出了其他字符。
44 //到这里提示:buffer corrupt!!
45 return 0;
46 }
原文链接: https://www.cnblogs.com/kevinGaoblog/archive/2012/07/20/2601069.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/56118
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!