2009-05-18 16 views
0

私はC + +でgrep関数を書いています(自己割り当ての練習として - これは実際のgrep機能の機能を持っていないことに気付きました)元の文字列と探している検索文字列を取得します。コードでは、grep文字列のすべての文字を最初のスペースまで入力します。次にgrep文字列の文字と検索文字列を比較し、一致する場合は一時文字列に格納します。私はgrep文字列をループし、一致するかどうかを調べるために検索文字列の長さを一時文字列と比較します。比較文字列サイズを比較文字の代わりに使用していますか?

私の質問:その長さを比較すると、悪いフォームですか?私はforループを使ってそれぞれのキャラクターをお互いに比較することができますが、CPUサイクルを不必要に食べるようです。ここに参考のために私の入力機能があります:

std::string grep(std::string originalStr, std::string searchStr) 
{ 
std::string grepStr = ""; 
std::string finalStr = ""; 
//stores final string; is the return value 
finalStr.resize(originalStr.length() + 1); 
grepStr.resize(originalStr.length() + 1); 

int place = 0; 
//remember where you are in originalStr[place] 
int numOfOccurences = 0; 
//remember number of times searchStr was found; 
//not necessary 
std::string tempStr = ""; 
//will temporarily hold grepStr  

//handles case if first occurence is a space 
if (originalStr[0] == ' ') 
{ 
    place++; 
} 

while (place != originalStr.length()) 
{ 
    tempStr = ""; 

    while (originalStr[place] != ' ') 
    { 

     if (originalStr[place] == ' ') 
     { 
      break; 
     } 

     grepStr[place] = originalStr[place]; 
     ++place; 
    } 

    ++place;//ensures you skip over the space next pass 

    for (int i = 0; i != grepStr.length(); i++) 
    { 
     if (grepStr[i] == searchStr[i]) 
     { 
      //if they are the same, append that char.. 
      tempStr[i] = grepStr[i]; 

      if (tempStr.length() == grepStr.length()) 
      //..then check for string length; if same, searchStr equals tempStr 
      //and you can append grepStr to the finalStr 
      {      
       for (int x = 0; x != finalStr.length(); x++) 
       { 
        finalStr[x] = grepStr[x]; 
       } 

       ++numOfOccurences; 
       //add one to the number of occurences in originalStr 
       finalStr += ' '; 
       //add a space IF you find the string 
      } 
     } 
    } 
} 

return finalStr; 
} 

答えて

4

いいえ、悪い形式ではありません。結局のところ、少なくともある意味では、2つの弦が等しい長さでない場合、2つの弦は等しいとは言えません。

Boyer-Mooreの文字列照合アルゴリズムとKnuth-Pratt-Morrisアルゴリズムを見てください。 J [sic!彼は本当にそれを綴ります。ムーアはnice pageです。

+0

Boyer-Mooreファスト・ストリング・サーチ・アルゴリズムに関するリンクが見つかりました。ありがとうございます! –

+0

嬉しいです。これは本当にクールなアルゴリズムの一種です。あなたはそれを速くマッチングさせることができます。 –

0

std :: stringを使用している場合、作成したバージョンよりもSTL検索関数が効率的に実行される可能性があります。文字列を部分文字列で検索することは既知の問題です。ライブラリのバージョンは可能な限り最適化されていると確信しています。

+2

あなたは楽しいことはありません。 ;-) –

+0

楽しいことはありませんか?ねえ、もし彼が自分の個人的な養成のために車輪を再創造したいのであれば、彼を止めるつもりはありません。しかし、私は彼が働く場所で働くことになった場合、彼の "Wheel2.0.0α"を維持したくありません。それは楽しいことではありません。 – jmucchiello

+0

申し訳ありませんが、私はC++で今すぐプログラムすることを学んでいます。私はfind関数に慣れていませんが、将来それを試して使用します。 – jkeys