string与char *,char[ ]的转换和使用

/* memcmp example */
#include <stdio.h>
#include <string.h>
#include <string>
#include<iostream>
using namespace std;
int main ()
{

      string s;
      char *p = "adghrtyh";
      s = p;
      cout<<"char *转string:"<<s<<endl;
      char q[]="hahahha";
      s = q;
      cout<<"char[]转string:"<<s<<endl;
    /string转char *;
      string s1 = "abcdefg";
      char *data;
      int len = s1.length();
      data = (char *)malloc((len+1)*sizeof(char));
      s1.copy(data,len,0);//从s1的0位置开始复制长度为len的字符串给data
      *(data+len)='\0';
      printf("data:%s\n",data);
      cout<<data<<endl;
    ///string转char[];
        char t[len+1];
        for(int i=0;i<len;i++)
        {
            t[i]=s1[i];
        }
        t[len]='\0';
        cout<<"t="<<t<<endl;

      char buffer1[] = "DWgaOtP12df0";
      string buffer2="DWgaOtP12Df0";
      cout<<buffer2<<endl;
      cout<<&buffer2<<endl;
      cout<<&buffer2[0]<<endl;
    if(memcmp(buffer1,&buffer2[0],buffer2.length())==0)
    {
        cout<<"true"<<endl;
        printf ("'%s' is greater than '%s'.\n",buffer1,&buffer2[0]);
    }
    else
    {
        cout<<"false"<<endl;
        printf ("'%s' is not greater than '%s'.\n",buffer1,&buffer2[0]);
    }

    return 0;
}

运行结果如下:
char *转string:adghrtyh
char[]转string:hahahha
data:abcdefg
abcdefg
t=abcdefg
DWgaOtP12Df0
0x6efe64
DWgaOtP12Df0
false
‘DWgaOtP12df0’ is not greater than ‘DWgaOtP12Df0’.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值