C++ 将字符串向量转换为*字符
结果:C++ 将字符串向量转换为*字符,c++,vector,C++,Vector,结果: temp[0] = "t"; temp[1] = "e"; temp[2] = "s"; temp[3] = "t"; temp[4] = "\0"; 我不知道查询的长度,所以这就是为什么我使用vector作为temp 查询的示例如下: 从用户选择id 最终结果应该是: elements[0] = "test"; 使用 然后呢, std::vector<std::string> getParameters(const char *query) { std::v
temp[0] = "t";
temp[1] = "e";
temp[2] = "s";
temp[3] = "t";
temp[4] = "\0";
我不知道查询的长度,所以这就是为什么我使用vector作为temp
查询的示例如下:
从用户选择id
最终结果应该是:
elements[0] = "test";
使用
然后呢,
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;
}
请参见使用
然后呢,
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;
}
请参见,以提供一种简洁明了的方法来解决您所要求的最后一步。即,将字符串向量连接成一个字符串:
#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;
}
只是为了提供一个简短而简洁的方法来解决您所要求的最后一步。即,将字符串向量连接成一个字符串:
#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要简单得多
std::string concatenated = std::accumulate(temp.begin(),temp.end(),string());
只有一个向量就足够了。当然,stringstream要简单得多
std::string concatenated = std::accumulate(temp.begin(),temp.end(),string());
您可以使用strlen查找查询的长度。或者将其放入std::字符串中。或者对int i=0进行循环;查询[i]!='\0'; I++。你把C风格字符串与C++字符串混淆了。C++字符串在结尾时不应该手动添加0。可以使用StruLn查找查询长度。或者将其放入std::字符串中。或者对int i=0进行循环;查询[i]!='\0'; I++。你把C风格字符串与C++字符串混淆了。C++字符串不应该在结尾手动添加0。更简单的是让TEMP成为一个字符串,那么你不需要做任何特别的事情。我同意。我并不是想为他的程序提供更好的解决方案,只是回答他问的concat问题。更简单的是,先把temp设为字符串,然后你就不需要做任何特殊的事情了。我同意。我不是想为他的计划提供更好的解决方案,只是想回答他提出的康卡特问题。
std::string concatenated = std::accumulate(temp.begin(),temp.end(),string());
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];
}
}