c++string 和 c-string

使用C语言编写的应用程序经常使用strcpy 等字符串复制函数、strcat等拼接函数,还经常使用strlen来确定字符串的长度;具有较强C语言背景的C++程序员编写的应用程序亦如此。这些C风格字符串作为输入的函数非常危险,因为它们会寻找终止空字符,如果程序员没有在字符数组末尾添加空字符,这些函数将跨越字符数组的边界
C++提供了 std::string,这是一种功能强大而安全的字符串操作方式。不同于字符数组(C风格字符串实现),std::string是动态的,在需要存储更多数据时其容量将增大。

可以互相转换:

#include <iostream>
#include <string>
using namespace std;
int main()
{
    char *cp="hello";
    char c_arr[]="hello";
    char c_arr2[]={'h','e','l','l','o'};

    // c-string --> string
    string s1(cp);//复制cp中的所有字符到s1中(除了末尾空字符'\0')
    string s2(c_arr,2);//复制c_arr两个字符到s2中
    string s3(c_arr2);//error,一直拷贝直到遇到'\0'

    // string --> c-string
    string str("hello");
    const char *cp=str.c_str();
}

需注意C++中string赋值越界的问题,给定内存后,大小(size)就固定了,要改变要用“+=”,或者“=”,使用[index]时,index范围必须在[0,size-1]。

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string temp;
    temp[0]='a';//越界赋值
    temp[1]='b';//越界赋值
    temp[2]='c';//越界赋值
    temp[3]='\0';//越界赋值
    cout<<temp[0]<<temp[1]<<temp[2]<<endl;
    cout<<&temp[0]<<" "<<&temp[1]<<" "<<&temp[2]<<" "<<endl;
    printf("%d %d %d %d\n",&temp,&temp[0],&temp[1],&temp[2]);

    cout <<temp.size()<<endl;//0,没有动态分配内存
    cout<<temp<<endl;//空
    cout<<"****";

    string str1 = "hello";//拷贝初始化(和c-string不同)
    string str2("world");
    str1[0] = 'H';
    str2[0] = 'W';
    cout<<str1<<endl;
    cout<<str2<<endl;

    char *c_str = "Hello";
    *c_str = 'h';//错误,因为Hello仍然在常量区,没有在堆区产生副本
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值