关于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 stringpos position of the first character to include
count length of the substring
Return value
number of characters copiedexample
#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; }
相关文章推荐
- JAVA 关于String的CompareTo方法即字典序比较
- C#中关于String.Equals(object,object)和(object==object )的比较
- java中关于String的equals()比较
- [转]整理关于java的String 类,equals函数和比较操作符的区别
- 关于Hashtable与ArrayList存储string的性能比较
- 关于String对象的比较
- 比较详细的关于javascript中void(0)的具体含义解释
- 对于上一篇文章的补充,关于String类型的比较
- 关于String比较的一些问题
- 关于String类型常亮进行“==” 和equal()比较的不同
- 关于proc的介绍,比较详细
- 0024 java中String创建比较最详细解释【入门】
- C/C++中关于std::string的compare陷阱示例详解
- 关于input比较详细博客
- 找了许久,终于找到一篇关于GStreamer架构的说的比较详细和底层的文章
- 关于String str =new String("abc")和 String str = "abc"的比较
- 关于java String的“==”和equals()比较、引用的小问题
- 转载的关于pthread_cond_wait的文章,写的比较详细
- 关于html5缓存部分比较详细的说明
- 关于SpannableString属性详细介绍以及利用SpannableString显示多种文本效果