您的位置:首页 > 运维架构

关于string::copy()的比较详细的示例

2012-07-20 13:59 387 查看

std::basic_string::copy

C++

Strings library

std::basic_string

size_type copy( CharT* dest, size_type count, size_type pos = 0);

Copies a substring [pos, pos+count) to character string pointed to by dest. If the requested substring lasts past the end of the string, or if count == npos, the copied substring is [pos, size()). The resulting character string is not null-terminated.

If pos >= size(), std::out_of_range is thrown.

Parameters

dest   pointer to the destination character string

pos   position of the first character to include

count  length of the substring

Return value

number of characters copied

example

#include <string>
#include <iostream>

using namespace std;

int main ()
{
size_t length;
char buffer[8];
string str("Test string......");

length=str.copy(buffer,7,6);       //从buffer6,往后数7个,相当于[ buffer[6], buffer[6+7] )
buffer[length]='\0';                        //加上'\0'使得buffer就到buffer[length]为止;

cout <<"buffer contains: " << buffer <<endl;

length=str.copy(buffer,str.size(),6);        //从buffer6,往后数7个,
                              //相当于[ buffer[6], buffer[6+7] )
buffer[length]='\0';                        //使得buffer就到buffer[length]为止;
cout <<"buffer contains: " << buffer <<endl;

length=str.copy(buffer,7,0);                //相当于[  buffer[0], buffer[7] )
buffer[length]='\0';

cout << "buffer contains: " << buffer <<endl;

length=str.copy(buffer,7);                   //缺省参数pos,默认pos=0;
                              //相当于[ buffer[0], buffer[7] )
buffer[length]='\0';
cout << "buffer contains: " << buffer <<endl;
length=str.copy(buffer,string::npos,6);      //相当于[ buffer[7], buffer[npos] )  
                            //buffer越界赋值,没有出错
buffer[length]='\0';
cout<<string::npos<<endl;                    //string::npos是4294967295
cout<<buffer[string::npos]<<endl;            //实际是越界访问,但没有出错,输出空
cout<<buffer[length-1]<<endl;                //实际是越界访问,但没有出错,输出了其他字符
cout << "buffer contains: " << buffer <<endl;
length=str.copy(buffer,string::npos);        //相当于[ buffer[0], buffer[npos] )
                            //buffer越界赋值,没有出错
buffer[length]='\0';
cout << "buffer contains: " << buffer <<endl;        //buffer越界
cout<<buffer[string::npos]<<endl;                    //越界访问,输出空
cout<<buffer[length-1]<<endl;             //越界访问,没有输出str最后一个字符,输出了其他字符。
                                              //到这里提示:buffer corrupt!!
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: