string赋值char的问题 大家帮帮下
string lone(str,str.find_first_of("ABCDEFGS",0), str.find_first_not_of("ABCDEFGS",str.find_first_of("ABCDEFGS",0)) - str.find_first_of("ABCDEFGS",0));
可以赋值lone上 但是主要是想复制到 char p[1000] 上 怎么搞 只能一行
[解决办法]
string类型赋值给char*类型要用string的一个成员函数:c_str。
string str;
…………………………
char *p;
p = str.c_str;
…………………………
还有,我也看不懂你要干什么
[解决办法]
成员函数data返回一个字符数组。
char p[100] = str.data;
[解决办法]
上面两个成员函数忘了加括号了
[解决办法]
先分解一下:
string lone(str,str.find_first_of("ABCDEFGS",0), str.find_first_not_of("ABCDEFGS",str.find_first_of("ABCDEFGS",0)) - str.find_first_of("ABCDEFGS",0));
<==>
string lone(str, n1, n2 - n1);
其中:
n1 = str.find_first_of("ABCDEFGS",0);
n2 = str.find_first_not_of("ABCDEFGS",str.find_first_of("ABCDEFGS",0))
<==> str.find_first_not_of("ABCDEFGS", n1);
这个意思是把str字符串的第n1+1个字符的n2 - n1个字符赋给lone字符串
用数组的话,只能用内存操作函数了
memcpy(memset(p, 0, sizeof(p)), str.data()+n1, n2 - n1);
解释一下为啥用memset,这个其实是有必要的,楼主应该是想要一个C风格的字符串,所以要保证最后以'\0'结尾,memset的原型是:
void * memset ( void * ptr, int value, size_t num );
如果要把其中的n1和n2都换成数组的那种,就要用string.h中的strstr函数了
假设str也是在数组中的,那n1和n2就换成这样的:
n1 = strstr(str, "ABCDEFGS") - str;
n2 = strpbrk(str + n1, "ABCDEFGS") - str;
C字符串的写法就是:
memcpy(memset(p, 0, sizeof(p)), str + n1, n2 - n1);
<==>
memcpy(memset(p, 0, sizeof(p)), strstr(str, "ABCDEFGS"), strpbrk(strstr(str, "ABCDEFGS"), "ABCDEFGS") - strstr(str, "ABCDEFGS"));
提醒一下:
代码没有经过测试,仅供参考
[解决办法]
#include <cstring>
//...
string lone=...;
char p[1000];
strncpy(p,lone.c_str(),999);p[999]=0;