2012-05-22 36 views
35

¿Cómo puedo encontrar el texto dado dentro de una cadena? Después de eso, me gustaría crear una nueva cadena entre eso y otra cosa. Por ejemplo ...Buscar texto en una cadena con C#

Si la cadena fue:

This is an example string and my data is here 

Y Quiero crear una cadena con lo que esté entre "mi" y "es" ¿cómo podría hacerlo? Lo siento, esto es bastante pseudo, pero espero que tenga sentido.

+1

Look at [** 'IndexOf' **] (http://msdn.microsoft.com/en-us/library/k8b1470s.aspx) y [** 'Substring' **] (http://msdn.microsoft.com/en-us/library/aka44szs.aspx). – mellamokb

+1

posible duplicado de [Buscar palabra (s) entre dos valores en una cadena] (http: // stackoverflow.com/questions/8082103/find-words-between-two-values-in-a-string) –

+0

Esta es una función de Buscar y Reemplazar en la que busca. No es solo un hallazgo, que IndexOf() o string.Contains() podrían manejar fácilmente. – Fandango68

Respuesta

97

Utilice esta función.

public static string getBetween(string strSource, string strStart, string strEnd) 
{ 
    int Start, End; 
    if (strSource.Contains(strStart) && strSource.Contains(strEnd)) 
    { 
     Start = strSource.IndexOf(strStart, 0) + strStart.Length; 
     End = strSource.IndexOf(strEnd, Start); 
     return strSource.Substring(Start, End - Start); 
    } 
    else 
    { 
     return ""; 
    } 
} 

Cómo se usa:

string text = "This is an example string and my data is here"; 
string data = getBetween(text, "my", "is"); 
+3

No puedo decirle cuán útil es su función corta, gracias. – Sabuncu

+0

Pero solo encuentra la (s) palabra (s) entre otras dos palabras. ¿Dónde está el componente de reemplazo, que pidió el OP? – Fandango68

5
string string1 = "This is an example string and my data is here"; 
string toFind1 = "my"; 
string toFind2 = "is"; 
int start = string1.IndexOf(toFind1) + toFind1.Length; 
int end = string1.IndexOf(toFind2, start); //Start after the index of 'my' since 'is' appears twice 
string string2 = string1.Substring(start, end - start); 
0

Si sabe que siempre se desea que la cuerda entre "mi" y "es", entonces siempre se puede hacer lo siguiente:

string message = "This is an example string and my data is here"; 

//Get the string position of the first word and add two (for it's length) 
int pos1 = message.IndexOf("my") + 2; 

//Get the string position of the next word, starting index being after the first position 
int pos2 = message.IndexOf("is", pos1); 

//use substring to obtain the information in between and store in a new string 
string data = message.Substring(pos1, pos2 - pos1).Trim(); 
18

Usted podría utilizar expresiones regulares:

var regex = new Regex(".*my (.*) is.*"); 
if (regex.IsMatch("This is an example string and my data is here")) 
{ 
    var myCapturedText = regex.Match("This is an example string and my data is here").Groups[1].Value; 
    Console.WriteLine("This is my captured text: {0}", myCapturedText); 
} 
36

Este es el forma más sencilla:

if(str.Contains("hello")) 
+12

Esto no es una solución en absoluto al problema. ¿Por qué está esto votado? – MichelZ

+11

Porque es la solución que estaba buscando para mi problema (que es diferente del problema de OP). Da la casualidad de que Google me llevó a esta página cuando busqué mi problema. –

1
static void Main(string[] args) 
    { 

     int f = 0; 
     Console.WriteLine("enter the string"); 
     string s = Console.ReadLine(); 
     Console.WriteLine("enter the word to be searched"); 
     string a = Console.ReadLine(); 
     int l = s.Length; 
     int c = a.Length; 

     for (int i = 0; i < l; i++) 
     { 
      if (s[i] == a[0]) 
      { 
       for (int K = i + 1, j = 1; j < c; j++, K++) 
       { 
        if (s[K] == a[j]) 
        { 
         f++; 
        } 
       } 
      } 
     } 
     if (f == c - 1) 
     { 
      Console.WriteLine("matching"); 
     } 
     else 
     { 
      Console.WriteLine("not found"); 
     } 
     Console.ReadLine(); 
    } 
+0

peor caso serra –

2

usted puede hacerlo de forma compacta como esto:

string abc = abc.Replace(abc.Substring(abc.IndexOf("me"), (abc.IndexOf("is", abc.IndexOf("me")) + 1) - abc.IndexOf("size")), string.Empty); 
+0

Esta es la respuesta correcta y verdadera a lo que el OP estaba pidiendo: una función Buscar y Reemplazar en uno. – Fandango68

1

@ excepción de la respuesta de Prashant, las respuestas anteriores han sido contestadas incorrectamente. ¿Dónde está la característica "reemplazar" de la respuesta? El OP preguntó: "Después de eso, me gustaría crear una nueva cadena entre eso y otra cosa".

Basado en la excelente respuesta de @ Oscar, he ampliado su función para que sea una función "Search And Replace" en uno.

Creo que la respuesta de @Prashant debería haber sido la respuesta aceptada por el OP, ya que reemplaza.

De todos modos, he llamado a mi variante - ReplaceBetween().

public static string ReplaceBetween(string strSource, string strStart, string strEnd, string strReplace) 
{ 
    int Start, End; 
    if (strSource.Contains(strStart) && strSource.Contains(strEnd)) 
    { 
     Start = strSource.IndexOf(strStart, 0) + strStart.Length; 
     End = strSource.IndexOf(strEnd, Start); 
     string strToReplace = strSource.Substring(Start, End - Start); 
     string newString = strSource.Concat(Start,strReplace,End - Start); 
     return newString; 
    } 
    else 
    { 
     return string.Empty; 
    } 
} 
1
string WordInBetween(string sentence, string wordOne, string wordTwo) 
     { 

      int start = sentence.IndexOf(wordOne) + wordOne.Length + 1; 

      int end = sentence.IndexOf(wordTwo) - start - 1; 

      return sentence.Substring(start, end); 


     } 
1

Aquí es mi función usando la función de Oscar Jara como modelo.

public static string getBetween(string strSource, string strStart, string strEnd) { 
    const int kNotFound = -1; 

    var startIdx = strSource.IndexOf(strStart); 
    if (startIdx != kNotFound) { 
     startIdx += strStart.Length; 
     var endIdx = strSource.IndexOf(strEnd, startIdx); 
     if (endIdx > startIdx) { 
     return strSource.Substring(startIdx, endIdx - startIdx); 
     } 
    } 
    return String.Empty; 
} 

Esta versión tiene como máximo dos búsquedas del texto. Evita una excepción lanzada por la versión de Oscar cuando se busca una cadena final que solo ocurre antes de la cadena de inicio, es decir, getBetween(text, "my", "and");.

El uso es el mismo:

string text = "This is an example string and my data is here"; 
string data = getBetween(text, "my", "is"); 
1
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Threading; 
using System.Diagnostics; 

namespace oops3 
{ 


    public class Demo 
    { 

     static void Main(string[] args) 
     { 
      Console.WriteLine("Enter the string"); 
      string x = Console.ReadLine(); 
      Console.WriteLine("enter the string to be searched"); 
      string SearchText = Console.ReadLine(); 
      string[] myarr = new string[30]; 
      myarr = x.Split(' '); 
      int i = 0; 
      foreach(string s in myarr) 
      { 
       i = i + 1; 
       if (s==SearchText) 
       { 
        Console.WriteLine("The string found at position:" + i); 

       } 

      } 
      Console.ReadLine(); 
     } 


    } 












     } 
Cuestiones relacionadas