2016-09-06 9 views
-1

単語の文字列を作成し、その文字列を同じ文字列で検索するプログラムを作成しようとしています。C#文字列上の単語を検索する

質問の前半は機能していますが、2番目の問題で問題が発生しています。プログラムは、最初と最後の単語を見つけますが、どのように最終的な中間の単語を見つけますか?それでは、どうやって数えますか?

 string strfinal; 
     string frase = "", texto = ""; 
     string textoAEncontrar; 
     Console.WriteLine("Insira algum texto (carregue no * para terminar a escrita): "); 

     for (texto = ""; !texto.Equals("*");) 
     { 
      texto = Console.ReadLine(); 
      if (texto.Length < 100) 
      { 
       frase = frase + " " + texto; 
      } 
     } 


     strfinal = frase.Substring(1, frase.Length - 2); 

     Console.WriteLine(strfinal); 

     Console.WriteLine("O que deseja encontrar no texto escrito: "); 
     textoAEncontrar = Console.ReadLine(); 
     int primeiraReferenciaNoTexto = strfinal.IndexOf(textoAEncontrar); 
     int ultimaReferenciaNoTexto = strfinal.LastIndexOf(textoAEncontrar); 


     if (strfinal.Contains(textoAEncontrar)) 
      { 

       Console.WriteLine("A palavra {0} existe no index {1}", textoAEncontrar, primeiraReferenciaNoTexto); 
       Console.WriteLine("A palavra {0} existe no index {1}", textoAEncontrar, ultimaReferenciaNoTexto); 
      } 
      else 
      { 
       Console.WriteLine("A palavra {0} não existe", textoAEncontrar); 
      } 



    } 
} 

答えて

1

あなたはそうのように、チェーンにあなたのIndexOf呼び出しを必要とする:

var i = -1 
while (true) 
{ 
    i = strFinal.IndexOf(textoAEncontrar, i+1); 
    if (i == -1) break; 
    Console.WriteLine("Found string at {0}", i); 
} 

あなたは上記の境界チェックを改善する必要があるかもしれませんが、これは一般的な考え方です。

+0

working great。ありがとうございました! –

0

このようなときは、RegExが間違いなく必要です。 RegExには.Matchが必要です。私たちは、文字列から数値を探しているので、

using System; 
using System.Text.RegularExpressions; 

class Program 
{ 
    static void Main() 
    { 
     Regex regex = new Regex(@"\d+"); 
     Match match = regex.Match("Dot 55 Perls"); 
     if (match.Success) 
     { 
      Console.WriteLine(match.Value); 
     } 
    } 
} 

、我々は55

はこれにさらに説明については下のリンクを参照してください取得します:

http://www.dotnetperls.com/regex

https://stackoverflow.com/a/2159085/5694113

0

メソッドを作成することができます文字列中の単語のn番目の出現のインデックスを取得します。区切り文字のスペースがあるので、text.Splitを使用してオカレンスの数を数えることもできます。

 static void Main(string[] args) 
     {  
      string text = "apple cinder apple goat apple"; 
      string searchWord = "apple"; 

      string[] textSplit = text.Split(' '); 

      int searchResultCount = textSplit.Where(s => s == searchWord).Count(); 

      Console.WriteLine(text); 
      Console.WriteLine(searchWord); 
      Console.WriteLine(searchResultCount); 
      Console.WriteLine(IndexOfOccurence(text, searchWord, 2)); 

      Console.ReadLine(); 
     } 

     static int IndexOfOccurence(string s, string match, int occurence) 
     { 
      int i = 1; 
      int index = 0; 

      while (i <= occurence && (index = s.IndexOf(match, index)) != -1) 
      { 
       if (i == occurence) 
        return index; 
       index++; 
       i++; 
      } 

      return -1; 
     } 
関連する問題