将字符串向量转换为 *字符
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] == ' ') {
temp.push_back(' ');
// 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(' ');
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] = " ";
结果:
elements[0] = "test";
我不知道查询的长度,所以这就是我使用向量作为温度的原因。
查询示例:
从用户中选择 ID
最终结果应该是:
elements[0] = "select";
elements[1] = "id";
elements[2] = "from";
elements[3] = "user";
使用 std::stringstream
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] == ' ') {
temp[j] = ' ';
elements.push_back((string)temp);
break;
}
if (query[i] == ' ')
{
temp[j] = ' ';
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());
相关文章:
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 尝试将字符串/字符转换为整数会产生意外结果
- 如何使用C++将字符串中的字符转换为整数变量
- 字符转换功能 std::isupper() & std::islower() C++17
- 将字符 * 转换为字符串 *
- 在编译时将常量字符* 转换为常量 char_type*
- 如何在 C/C++ 中将无符号字符*转换为无符号字符数组?
- 错误:请求从"常量字符 [5]"转换为非标量类型"字符串"
- 无法使用字符串流将字符转换为字符串C++
- 将无符号字符 C++ 转换为 C#
- C++:使用没有位移位的指针将无符号字符转换为无符号 int
- 为什么我可以隐式地将字符*转换为常量字符*,但不能将无符号字符*
- 无法<string>从"常量字符 []"转换为<类名>
- 不能将字符转换为整数吗?
- 编译时将字符*转换为字节
- CP1251:从字符* 转换为 wchar_t* 时的编码失真
- 将单个字符转换为 std::string 前缀 \x01
- PPM 将字符转换为 int 授予负数
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类
- 将常量字符* 转换为字符时出错