-4

いくつかの奇妙な理由により、さまざまな他の文字列に分割され、区切り文字を使用してベクトル文字列内に配置されることを意図した元の文字列は、うまく機能しません。そして、私は自分の間違いを見つけることができないようです。

#include <iostream>
#include <vector>
#include <string>

using namespace std;

vector<string> split(string target, string delimiter);

int main()
{
    split ("1,2,3,4,5",",");
    return 0;
}

vector<string> split(string target, string delimiter)
{
    vector<string> word;
    string letter;
    int i = 0;
    int k = 0;

    while (target[i] != '\0')
    {
        word.empty();
        word.push_back("target");
        while (target[i] != delimiter[0])
        {
            letter = target[i];
            i++;
        }
        word[i]=letter;
        i++;

    }
    return (word);
}
4

1 に答える 1

0

最初の問題は、 を呼び出すときですsplit。2 番目のパラメーターは単一のスペースを含む文字列ですが、分割する文字列はコンマで区切られています。コメント セクションでH2CO3によって既に言及されている他の問題は、完全を期すために以下に強調表示されています。

  1. while ループの反復ごとにベクトルを空にしています。
  2. すべての反復中に文字列「ターゲット」を追加しています。
  3. ベクトルに単一の文字を追加しています。代わりに、文字列全体を追加する必要があります。
  4. 区切り文字と抽出する個々の文字列が 1 文字よりも大きい可能性があることを考慮していません。
  5. 文字列内の区切り文字を一致させるための全体的なロジックが間違っています (少なくとも現在実装している方法では)。最初の文字のみを比較しています。それが望ましい動作である場合は、タイプをdelimiterに変更しstring::value_typeます。
  6. それ自体は問題ではありませんがconst、値ではなく参照によって文字列を渡すことをお勧めsplitします。

以下の例は、標準ライブラリに既に存在する機能を活用する方法をよりよく理解するのに役立ちます。データに直接アクセスするのではなく、findおよびsubstrのメンバー関数を使用します。先に進む前に、とstd::stringのドキュメントを確認することをお勧めします。std::vectorstd::string

std::vector<std::string>
    split(const std::string& target, const std::string& delimiter)
{
    std::vector<std::string> word;
    size_t start = 0;

    for(;;)
    {
        size_t loc = target.find(delimiter, start);

        if(loc == std::string::npos)
        {
            word.push_back(&target[start]);
            break;
        }

        word.push_back(target.substr(start, loc - start));
        start += (loc - start) + delimiter.size();
    }

    return (word);
}
于 2013-05-26T19:21:44.477 に答える