将字符串向量转换为 *字符

Convert string vector to *char

本文关键字:字符 转换 字符串 向量      更新时间:2023-10-16
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());