char[ ] 强转为 标准库类型string

今天看到一条语句,如下:
char数组转string
知道char 数组可以和string 相互转换,但是自己从来没有做过。。。

举个栗子:

#include <iostream>
#include <string>
using namespace std;

int main(){
    char a[]={'1','2','3','4','5'};
    string str=string(a+1);
    string str2=string(a);
    cout<<str<<endl;
    cout<<str2<<endl;
    return 0;
}

结果:

2345
12345

分析:
可以直接 用 数组名 强制转换 为string,结果包含所有的数组元素。
也可以 用 数组名+偏移量 的形式转换为string,结果不包含偏移量之前的元素。

注:
如果想要处理 string 类型对象的每一个字符,可以用 range for,外加< cctype > 标准库头文件里提供的一些对字符处理的函数。
比如,
isalnum(c)
isalpha(c)
isprint(c)
isspace(c)
toupper(c)等

猜你喜欢

转载自blog.csdn.net/fsdgsddaer/article/details/80091901
今日推荐