void getParameters(char *query) {
vector<string> temp;
vector<string> elements;
for (int i = 0; i < 10; i++)
{
if (query[i] == '\0') {
temp.push_back('\0');
// Here I want to convert temp values to string and append it to elements
elements.push_back(temp);
break;
}
if (query[i] == ' ')
{
temp.push_back('\0');
elements.push_back(temp);
temp.clear();
continue;
}
temp.push_back(query[i]);
}
}
我想将 temp 向量的所有值附加到元素向量的字符串。
例如:
temp[0] = "t";
temp[1] = "e";
temp[2] = "s";
temp[3] = "t";
temp[4] = "\0";
结果:
elements[0] = "test";
我不知道查询的长度,所以这就是我为 temp 使用vector的原因。
查询:
的示例从用户
中选择ID
最终结果应为:
elements[0] = "select";
elements[1] = "id";
elements[2] = "from";
elements[3] = "user";
答案 0 :(得分:2)
std::vector<std::string> getParameters(const char *query)
{
std::vector<std::string> elements;
std::stringstream ss(query);
std::string q;
while (ss >> q)
elements.push_back(q);
return elements;
}
然后,
char *s="select id from user";
std::vector<std::string> elements= getParameters(s);
请参阅HERE
答案 1 :(得分:1)
#include <sstream>
#include <vector>
#include <string>
std::vector<std::string> getParameters(const char *query) {
std::ostringstream split(query);
std::vector<std::string> elements;
std::string element;
while (split >> element)
elements.push_back(element);
return elements;
}
答案 2 :(得分:1)
只有一个向量就足够了。当然,stringstream
要简单得多。
void getParameters(char *query) {
const int length = 10;
char temp[length];
vector<string> elements;
for (int i = 0, j = 0; i < 10; i++, j++)
{
if (query[i] == '\0') {
temp[j] = '\0';
elements.push_back((string)temp);
break;
}
if (query[i] == ' ')
{
temp[j] = '\0';
elements.push_back((string)temp);
j = -1;
continue;
}
temp[j] = query[i];
}
}
答案 3 :(得分:0)
string str1 = "helo";
string str2 = "world";
string str = str1 + str2;
const char *cstr = str.c_str();
答案 4 :(得分:0)
只是为解决你要求的最后一步提供一个简洁而简洁的方法。即将字符串向量连接成一个单独的字符串:
std::string concatenated = std::accumulate(temp.begin(),temp.end(),string());