【问题标题】:C++ function split string into wordsC ++函数将字符串拆分为单词
【发布时间】:2013-10-02 13:04:46
【问题描述】:

我试图在 C++ 中编写一个函数,将我的字符串测试拆分为数组中的单独单词。我似乎无法正确循环中的内容...有人有任何想法吗?它应该打印“this”

void app::split() {

    string test = "this is my testing string.";

    char* tempLine = new char[test.size() + 1];
    strcpy(tempLine, test.c_str());

    char* singleWord;

    for (int i = 0; i < sizeof(tempLine); i++) {

        if (tempLine[i] == ' ') {
            words[wordCount] = singleWord;
            delete[]singleWord;
        }

            else {
            singleWord[i] = tempLine[i];
            wordCount++;

            }

    }

    cout << words[0];
    delete[]tempLine;


}

【问题讨论】:

  • 这是一种重新发明轮子。为什么不使用字符串流的默认行为?
  • 两个 cmets:(a) 是什么阻止你自己调试这个? (你知道如何使用调试器,对吧?)和 (b) 如果这应该是 C++,那么为什么要使用裸指针和 C 风格的编程?
  • sizeof(tempLine) 等价于使用 x86 架构中的 4(32 位)sizeof(char*)。您可以使用 strlen(tempLine) 获取字符串的长度。另外,我建议您使用 std::vector 而不是原始 char[] 数组。
  • 你也可以使用 string::substr() 函数来获取原始字符串的一部分。
  • 您想学习基础知识(例如数组和指针)还是高级功能(例如标准容器和stringstream)?

标签: c++ string function split words


【解决方案1】:

如果您只想显示字符串中的单词,请使用:

#include <algorithm>
#include <iterator>
#include <sstream>
//..
   string test= "this is my testing string.";
        istringstream iss(test);
        copy(istream_iterator<string>(iss),
                 istream_iterator<string>(),
                 ostream_iterator<string>(cout, "\n"));

如果要处理这些单词,则使用 std::vector of std::string

     std::vector<std::string> vec;

        istringstream iss(test);
        copy(istream_iterator<string>(iss),
                 istream_iterator<string>(),
                 back_inserter(vec));

【讨论】:

  • istringstream 真的很酷。但我想将它们存储在一个数组或其他东西中,这样我就可以用不同的算法打印单词
  • 你可以从迭代器初始化向量:vector&lt;string&gt;vec {istream_iterator&lt;string&gt;(iss), istream_iterator&lt;string&gt;()};
猜你喜欢
  • 2011-06-12
  • 1970-01-01
  • 2011-10-23
  • 2014-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 2011-11-03
相关资源
最近更新 更多