[英]Convert string vector to *char
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[0] = "t";
temp[1] = "e";
temp[2] = "s";
temp[3] = "t";
temp[4] = "\0";
結果:
elements[0] = "test";
我不知道查詢的長度,所以這就是為什么我將vector用於temp的原因 。
查詢示例:
從用戶中選擇ID
最終結果應為:
elements[0] = "select";
elements[1] = "id";
elements[2] = "from";
elements[3] = "user";
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);
見這里
#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;
}
僅一個向量就足夠了。 當然, 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];
}
}
string str1 = "helo";
string str2 = "world";
string str = str1 + str2;
const char *cstr = str.c_str();
只是為了提供一種簡潔的方法來解決您要求的最后一步。 即將字符串向量連接成一個字符串:
std::string concatenated = std::accumulate(temp.begin(),temp.end(),string());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.