/* 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’.