2016-09-06 5 views
-1

단어의 문자열을 만든 다음 동일한 문자열에서 해당 단어를 찾는 프로그램을 만들려고합니다.C# 문자열에서 단어를 찾으십시오.

질문의 전반부가 작동하지만 두 번째 문제가 있습니다. 프로그램은 처음과 마지막으로 단어를 찾습니다. 그러나 어떻게 중간에 하나의 단어를 찾았습니까? 그런 다음 어떻게 계산합니까?

 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

위대한 작품입니다. 고맙습니다! –

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; 
     } 
관련 문제