[英]How to change string s to char * a[]?
I want to transform 我想改造
string s="aaa,bbb,ccc"
into: 成:
char * a[]={"aaa", "bbb", "ccc"}
Could you help me how to program for dealing with this process? 你能帮我解决一下处理这个过程的程序吗?
I will try to program like this: 我会尝试像这样编程:
string s="aaa,bbb,ccc";
char * a[];
char id[] = "";
strcpy(id, s.c_str());
const char * split = ",";
char * p;
p = strtok(id, split);
while (p != NULL) {
int i = 0;
printf("%s\n", p);
a[i]=p;
i++;
p = strtok(NULL, split);
}
where is my wrong? 我哪里错了? who can point out ?
谁可以指出?
I'm new to programming, but I've been doing the following: 我是编程的新手,但我一直在做以下事情:
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
std::string s = "aaa,bbb,ccc";
// dynamically allocate memory for the char
char * a = new char [s.length()+1];
// the string needs to be copied into a
std::strcpy(a, s.c_str());
std::cout << a;
// cleanup
delete [] a;
return 0;
}
Edit: Just noticed you want the different parts of the string as elements of the char array, my answer doesn't do that. 编辑:刚刚注意到你想要字符串的不同部分作为char数组的元素,我的答案不会这样做。
I suggest to use a std::vector<std::string>
to store your results instead of char* []
, it should be more useful. 我建议使用
std::vector<std::string>
来存储结果而不是char* []
,它应该更有用。
So, try this one , purely C++ std library. 所以,试试这个 ,纯粹的C ++ std库。
But if you surely need a char* []
, I suggest that write a converter function, , like: 但如果你肯定需要一个
char* []
,我建议写一个转换器函数,如:
char** ToCharArrays(const std::vector<std::string>& strings)
{
char** cs = new char* [strings.size()];
for (int i = 0, l = strings.size(); i < l; ++i)
{
cs[i] = const_cast<char*>(strings[i].c_str());
}
return cs;
}
Use case is like this: 用例是这样的:
std::string input("aaa,bbb,ccc");
std::vector<std::string> strings = Split(input, ',');
char** asCharArrays = ToCharArrays(strings);
YourAPINeedsCharArrays(asCharArrays, strings.size());
delete[] asCharArrays;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.