c++中怎么把string转化为数组

  1. 因为string可以看作是数组构成的串,所以直接定义一个char的指针,指过去就可以了。
    示例如下:
#include <windows.h>  
#include <stdio.h>  
#include <time.h> 
#include <iostream>
using namespace std;
int main()
{
 
    string s1 = "abcdeg"; //定义string
    const char *k; //定义char指针
    k = s1.c_str(); //让指针指向s1的位置
 
    cout << k[0] << endl; //测试输出k指针指向的第一个字符
 
    system("pause"); //暂停一下以便查看
    return 0;  //标准的返回退出
 
}
  1. 比较机械的,先定义一个字符数组,然后将字串的内容“复制”进去。这种方法更规矩一些,也更安全一些:
#include <windows.h>  
#include <stdio.h>  
#include <time.h> 
#include <iostream>
using namespace std;
 
 
int main()
{
 
    string s = "a1234";
    char c[20];
    strcpy(c, s.c_str());  //trcpy()函数的作用是将指定的字符串进行拷贝,该函数无法拷贝string对象,只能拷贝string对象的c_str()函数返回的字符串
 
    cout << c[0] << endl;
 
    system("pause");
    return 0;
 
}
  • 7
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值