在不使用向量的情况下,将字符串分割成C ++中的数组

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在不使用向量的情况下,将字符串分割成C ++中的数组相关的知识,希望对你有一定的参考价值。

我正在尝试使用C ++中的vector将由空格分隔的字符串插入字符串数组[[without。例如:

using namespace std; int main() { string line = "test one two three."; string arr[4]; //codes here to put each word in string line into string array arr for(int i = 0; i < 4; i++) { cout << arr[i] << endl; } }
我希望输出为:

test one two three.

我知道在C ++中还有其他问题要问字符串>数组,但是我找不到满足我条件的答案:不使用向量将字符串拆分成数组。
答案
可以通过使用std::stringstream类将字符串转换为流(其构造函数将字符串作为参数)。构建完成后,您可以在其上使用std::stringstream运算符(例如在基于常规文件的流上),该运算符将从中提取或

tokenize单词:

>>
另一答案
#include <iostream> #include <sstream> using namespace std; int main(){ string line = "test one two three."; string arr[4]; int i = 0; stringstream ssin(line); while (ssin.good() && i < 4){ ssin >> arr[i]; ++i; } for(i = 0; i < 4; i++){ cout << arr[i] << endl; } }
另一答案
#include <iostream> #include <sstream> #include <iterator> #include <string> using namespace std; template <size_t N> void splitString(string (&arr)[N], string str) { int n = 0; istringstream iss(str); for (auto it = istream_iterator<string>(iss); it != istream_iterator<string>() && n < N; ++it, ++n) arr[n] = *it; } int main() { string line = "test one two three."; string arr[4]; splitString(arr, line); for (int i = 0; i < 4; i++) cout << arr[i] << endl; }
另一答案

Trivial:

#define MAXSPACE 25 string line = "test one two three."; string arr[MAXSPACE]; string search = " "; int spacePos; int currPos = 0; int k = 0; int prevPos = 0; do { spacePos = line.find(search,currPos); if(spacePos >= 0) { currPos = spacePos; arr[k] = line.substr(prevPos, currPos - prevPos); currPos++; prevPos = currPos; k++; } }while( spacePos >= 0); arr[k] = line.substr(prevPos,line.length()); for(int i = 0; i < k; i++) { cout << arr[i] << endl; }
const vector<string> explode(const string& s, const char& c)
{
    string buff{""};
    vector<string> v;

    for(auto n:s)
    {
        if(n != c) buff+=n; else
        if(n == c && buff != "") { v.push_back(buff); buff = ""; }
    }
    if(buff != "") v.push_back(buff);

    return v;
}
另一答案
这里是一个建议:在字符串中使用两个索引,例如Follow linkstartend指向要提取的下一个字符串的第一个字符,start指向要提取的下一个字符串的最后一个字符之后的字符。 end从零开始,start获取在end之后的第一个字符的位置。然后,将start之间的字符串添加到数组中。您一直努力直到到达字符串的末尾。
另一答案
[start..end)
输出:-

分割上空格

以上是关于在不使用向量的情况下,将字符串分割成C ++中的数组的主要内容,如果未能解决你的问题,请参考以下文章

如何在不使用 R 中的表的情况下对分类值的实例求和?

如果只需要结果的低位部分,哪些 2 的补码整数运算可以在不将输入中的高位归零的情况下使用?

如果只需要结果的低部分,哪些 2 的补码整数运算可以在不将输入中的高位归零的情况下使用?

C/C++ Linux,如何在不使用 IP 的情况下在网络上查找邻居(仅限 MAC)

如何在不使用 numpy 的情况下计算 python 中的标准偏差?

在不使用字符串的情况下将图像上传到android中的服务器