2016-12-15 13 views
1

は、私は私が使用しているので、ユーザーが選択したウェブサイトを訪問しようとしている簡単なプログラムを作成していif文のような:if文で*ワイルドカードを使用するにはどうすればよいですか?

If (url == "http://") 
{ 
    cout << ("Connecting to ") << url; 
} 
else 
{ 
    cout << ("Invalid URL"); 
} 

そして私は、私はdoesnの文字列をフィルタすることができますどのように思ったんだけど「http://」または「https://」で始まっていない、私はちょうど助けていただければ幸いです。

+4

'find'を使用して0を返すかどうかをチェックします。 – NathanOliver

+0

@ NathanOliverしかし、それは' otherstuffhttp:// otherstuff'のように一致します – Max

+1

http://stackoverflow.com/questions/1878001/how-do-iの可能な複製-check-if-ac-string-starts-with-certain-string-and-convert-a-sub – Max

答えて

1

明確ではなく、特に、高速道、(urlstd::stringであると仮定した場合)を使用することである

ここ
if (url.substr(0, 7) != "http://" && url.substr(0, 8) != "https://"){ 
    /*I don't start with http:// or https:// */ 
} 

私は、オーバーロード!=演算子を使用して、その後std::stringの開始を抽出するためにsubstrを使用しています。

urlが7文字または8文字よりも短い場合、動作はまだよく定義されています。

static const char HTTP[] = "http://"を定義し、sizeof(HTTP) - 1 &cを使用できます。長さをハードコーディングすることはありませんが、それはあまりにも遠すぎるかもしれません。

の正規表現の暗い世界に近づくためには、もっと一般性があります。 std::regexを参照してください。

1

可能なオプションは、既知の開始プロトコルを文字列のベクトルに格納し、そのベクトルとその関数と文字列関数を使用してテストを行い、URLが文字列オブジェクトの比較であれば簡単です。あなたはだけでなく、機能にURLの両方を渡すことができますこの方法を次のステップにこれを取るとシンプルな機能に

#include <string> 
#include <vector> 

void testUrls(const std::string& url, const std::vector<std::string>& urlLookUps) { 

    std::vector<unsigned int> sizes; 

    for (unsigned int idx = 0; idx < urlLookUps.size(); ++idx) { 
     sizes.push_back(urlLookUps[idx].size()); 
    } 

    bool foundIt = false; 
    for (unsigned int idx = 0; idx < urlLookUps.size(); ++idx) { 
     if (url.compare(0, sizes[idx], urlLookUps[idx]) == 0) { 
      foundIt = true; 
      break; 
     } 
    } 

    if (foundIt) { 
     std::cout << url << std::endl; 
    } else { 
     std::cout << "Invalid URL" << std::endl; 
    } 

} // testUrls 

int main() { 
    const std::vector<std::string> urlLookUps { "http://", "https://" }; 
    std::string url1("http://www.home.com"); 
    std::string url2("https://www.home.com"); 
    std::string url3("htt://www.home.com"); 

    testUrl(url1, urlLookUps); 
    testUrl(url2, urlLookUps); 
    testUrl(url3, urlLookUps); 

    return 0; 
} // main 

それを回すことができる

#include <string> 
#include <vector> 

int main { 
    const std::vector<std::string> urlLookUps { "http://", "https://" }; 

    std::string url("https://www.home.com"); 

    unsigned int size1 = urlLookUps[0].size(); 
    unsigned int size2 = urlLookUps[1].size(); 

    if (url.compare(0, size1, urlLookUps[0]) == 0 || 
     url.compare(0, size2, urlLookUps[1]) == 0) { 
     std::cout << url << std::endl; 
    } else { 
     std::cout << "Invalid Address" << std::endl; 
    }     

    return 0; 
} 

EDIT

ユーザーが自分自身を作成し​​たいと思うかもしれないURLプロトコルのコンテナ。このようにして、関数は文字列のベクトルに保存されているすべての文字列を検索します。

関連する問題