1

std::stringURLを含むをそのコンポーネントに分割するC++関数を作成しようとしています。コンポーネントをこの構造にコピーする必要があります。

typedef struct urlstruct {
    string protocol;
    string address;
    string port;
    string page;
} urlstruct;

これまでの関数は次のとおりです。

int parseAnnounce2(string announce, urlstruct *urlinfo){
    int i;

    if(announce.find("://") != string::npos){
        // "://" found in string, store protocol
        for(i = 0; i < announce.find("://"); i++){

        }
    } else {
        // No "://" found in string
    }

    return 0;
}

'://'シーケンスの前の文字をurlinfo->protocol文字列にコピーする必要があります。これを行うための良い方法は何ですか?

プロトコル文字列がそのメモリを含むように初期化されていないため、次のコード行を使用して割り当てることができないことを知っています。

urlinfo->protocol[i] = announce[i];
4

3 に答える 3

5

を使用しstd::string::assignます。これは機能するはずです:

if (announce.find ("://") != std::string::npos)
    urlinfo->protocol.assign (announce, 0, announce.find ("://"));
else
    //not found, handle

または、結果を変数に格納して、find2回計算/入力しないようにする場合は、次のようにすることもできます。

std::string::size_type foundPos = announce.find ("://");
if (foundPos != std::string::npos)
    urlinfo->protocol.assign (announce, 0, foundPos);
else
    //not found, handle
于 2012-07-21T17:03:14.087 に答える
2

std::string::insertここで仕事をする必要があります:

size_t pos = announce.find("://");
if(pos != std::string::npos)
{
    protocol.insert(0, announce, 0, pos);
}
于 2012-07-21T17:03:30.547 に答える
0

もう1つのオプションは、std :: string :: substr()を使用することです。この関数に必要なすべての情報がすでにあります。

于 2012-07-21T20:59:50.723 に答える