版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/89761721
一 点睛
函数原型:
size_t copy (char* s, size_t len, size_t pos = 0) const;
函数功能:
copy函数的作用是从string对象中取出若干字符存放到数组s中。其中,s是字符数组,n表示要取出字符的个数,pos表示要取出字符的开始位置。
函数参数:
-
参数s:字符数组,用来存放从string对象取出的字符。
-
参数len:取出的字符个数。
-
参数pos:要取出的字符在string对象中的开始位置。
函数的返回值:
函数返回取出字符的个数。
二 实战
#include<iostream>
#include<string>
using namespace std;
int main (){
size_t length;
char buffer[8];
string str("Test string......");
cout<<"str:"<<str<<endl;
length=str.copy(buffer,7,5);
buffer[length]='\0';
cout<<"str.copy(buffer,7,5),buffer contains: "<<buffer<<endl;
length=str.copy(buffer,str.size(),5);
buffer[length]='\0';
cout<<"str.copy(buffer,str.size(),5),buffer contains:"<<buffer<<endl;
length=str.copy(buffer,7,0);
buffer[length]='\0';
cout<< "str.copy(buffer,7,0),buffer contains:"<<buffer<<endl;
length=str.copy(buffer,7); //缺省参数pos,默认pos=0
buffer[length]='\0';
cout<<"str.copy(buffer,7),buffer contains:"<<buffer<<endl;
length=str.copy(buffer,string::npos,5); //copy函数第2个参数,除了可以是长度,也可以是一个位置,string::npos表示字符串的结束位置
buffer[length]='\0';
cout<<"string::npos:"<<(int)(string::npos)<<endl;
cout<<"buffer[string::npos]:"<<buffer[string::npos]<<endl;
cout<<"buffer[length-1]:"<<buffer[length-1]<<endl;
cout<<"str.copy(buffer,string::npos,5),buffer contains:"<<buffer<<endl;
length=str.copy(buffer,string::npos);
buffer[length]='\0';
cout<<"str.copy(buffer,string::npos),buffer contains:"<<buffer<<endl;
cout<<"buffer[string::npos]:"<<buffer[string::npos]<<endl;
cout<<"buffer[length-1]:"<<buffer[length-1]<<endl;
return 0;
}
三 运行
[root@localhost charpter03]# g++ 0305.cpp -o 0305
[root@localhost charpter03]# ./0305
str:Test string......
str.copy(buffer,7,5),buffer contains: string.
str.copy(buffer,str.size(),5),buffer contains:string......
str.copy(buffer,7,0),buffer contains:Test st
str.copy(buffer,7),buffer contains:Test st
string::npos:-1
buffer[string::npos]:
buffer[length-1]:.
str.copy(buffer,string::npos,5),buffer contains:string......
str.copy(buffer,string::npos),buffer contains:Test string......
buffer[string::npos]:
buffer[length-1]:.