2012-05-22 15 views
35

Jak znaleźć tekst w ciągu znaków? Potem chciałbym stworzyć nowy ciąg między tym a czymś innym. Na przykład ...Znajdź tekst w ciągu znaków z C#

Jeśli ciąg był:

This is an example string and my data is here 

I chcę utworzyć ciąg z tym, co jest między „my” i „jest” jak mogę to zrobić? Przepraszam, to jest dość pseudo, ale mam nadzieję, że ma to sens.

+1

Spójrz [** 'IndexOf' **] (http://msdn.microsoft.com/en-us/library/k8b1470s.aspx) i [** 'Substring' **] (http://msdn.microsoft.com/en-us/library/aka44szs.aspx). – mellamokb

+1

możliwy duplikat [Znajdź słowo (słowa) między dwiema wartościami w ciągu] (http: // stackoverflow.com/questions/8082103/find-words-between-two-values-in-a-string) –

+0

Jest to jednocześnie funkcja Znajdź i zamień w jednym z nich. To nie jest tylko znalezisko, które IndexOf() lub string.Contains() może łatwo obsłużyć. – Fandango68

Odpowiedz

97

Użyj tej funkcji.

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 ""; 
    } 
} 

Jak go używać:

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

Nie mogę powiedzieć, jak użyteczna jest twoja krótka funkcja - dzięki. – Sabuncu

+0

Ale znajduje tylko słowo (słowa) pomiędzy dwoma innymi słowami. Gdzie jest element zamienny, o który PO zadawał? – 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

Jeśli wiesz, że zawsze chcesz ciąg między "my" i "jest", to zawsze można wykonać następujące czynności:

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

można użyć wyrażenia regularnego:

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

to Najprostszy sposób:

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

To wcale nie jest rozwiązanie problemu. Dlaczego jest to wznawiane? – MichelZ

+11

Ponieważ jest to rozwiązanie, którego szukałem dla mojego problemu (który różni się od problemu OP). Tak się składa, że ​​Google zabrał mnie na tę stronę, gdy szukałem mojego problemu. –

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

najgorszy przypadek serach –

2

Można to zrobić kompaktowo tak:

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

To jest prawdziwa i prawidłowa odpowiedź na pytanie OP - funkcja Znajdź i zamień w jednym. – Fandango68

1

wyjątkiem @ Prashant odpowiedź na powyższe odpowiedzi zostały wysłuchane nieprawidłowo. Gdzie jest funkcja "zastąp" odpowiedzi? OP zapytał: "Po tym chciałbym stworzyć nowy ciąg między tym a czymś innym".

Na podstawie doskonałej odpowiedzi @ Oscara, rozszerzyłem jego funkcję o funkcję "Search And Replace" w jednym.

Myślę, że @ Odpowiedź Prashanta powinna była być zaakceptowaną odpowiedzią PO, ponieważ zastępuje.

W każdym razie nazwałem mój wariant - 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

Oto moja funkcja użyciem funkcji Oscar Jara jako model.

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; 
} 

Ta wersja zawiera co najwyżej dwa wyszukiwania tekstu. Uniknie wyjątku rzucanego przez wersję Oscara podczas wyszukiwania łańcucha końcowego, który występuje tylko przed łańcuchem początkowym, tj. getBetween(text, "my", "and");.

użycia jest taki sam:

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(); 
     } 


    } 












     } 
Powiązane problemy