104

How can I find given text within a string? After that, I'd like to create a new string between that and something else. For instance, if the string was:

This is an example string and my data is here

And I want to create a string with whatever is between "my " and " is" how could I do that? This is pretty pseudo, but hopefully it makes sense.

dakab
  • 5,379
  • 9
  • 43
  • 67
Wilson
  • 8,570
  • 20
  • 66
  • 101
  • 2
    Look at [**`IndexOf`**](http://msdn.microsoft.com/en-us/library/k8b1470s.aspx) and [**`Substring`**](http://msdn.microsoft.com/en-us/library/aka44szs.aspx). – mellamokb May 22 '12 at 20:41
  • 1
    possible duplicate of [Find word(s) between two values in a string](http://stackoverflow.com/questions/8082103/find-words-between-two-values-in-a-string) – Evan Mulawski May 22 '12 at 20:43
  • This is both a Find and Replace function in one you're after. It's not just a find, which IndexOf() or string.Contains() could easily handle. – Fandango68 Aug 24 '16 at 00:37
  • If you came here feeling like a crazy person because your UWP app's source didn't let you access `string` or `String`'s `.Contains()` and only `.Concat...` options, save, close, reboot, and save yourself some misery. – kayleeFrye_onDeck Jun 28 '19 at 05:55

17 Answers17

220

Use this method:

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

    return "";
}

How to use it:

string source = "This is an example string and my data is here";
string data = getBetween(source, "my", "is");
Yousha Aleayoub
  • 4,532
  • 4
  • 53
  • 64
Oscar Jara
  • 14,129
  • 10
  • 62
  • 94
  • 7
    Can't tell you how useful your short function is - thanks. – Sabuncu Jul 07 '15 at 08:55
  • But it only finds the word(s) inbetween two other words. Where is the replace component, which the OP asked? – Fandango68 Aug 24 '16 at 00:38
  • Nice function and also an upvote! Please include in your example what the output is for others to reference :) – Gareth Dec 04 '18 at 00:17
  • 3
    Great function! Please change the local variable names to start with lower case. You can also change `strSource.IndexOf(strStart, 0)` to `strSource.IndexOf(strStart)`. You don't have to declare `int start, end`, you can just write `int start = strSource.IndexOf....` – BornToCode Oct 29 '20 at 21:14
  • Console.WriteLine(getBetween("123", "2", "1")); System.ArgumentOutOfRangeException: 'Length cannot be less than zero. (Parameter 'length ')' –  Jul 26 '22 at 11:01
  • Doesn't this search strSource for strStart and strEnd twice, once for the two Contains calls, and again for the two IndexOf calls? Since IndexOf returns -1 when the string is not found, you could just call IndexOf, and check for -1 to catch the cases where strStart or strEnd do not occur. – Paul Sinclair Apr 04 '23 at 14:14
88

This is the simplest way:

if(str.Contains("hello"))
Kemal Duran
  • 1,478
  • 1
  • 13
  • 19
  • 31
    This is not a solution at all to the problem. Why is this upvoted? – MichelZ Jun 02 '15 at 14:49
  • 34
    Because it's the solution I had been looking for for my problem (which is different from OP's problem.). It just so happens that Google got me to this page when I searched for my problem. – Davide Andrea Jul 28 '15 at 20:41
  • 11
    Yes, but the answers are about the problem of the OP, not some random stuff... :) – MichelZ Jun 11 '18 at 06:50
  • 2
    Agree. Plus I was searching for something similar to the original post question on google, got to this page, and I got confused by this answer which is not what I am looking for. – Fabio Strocco Sep 04 '18 at 11:01
  • 1
    Well the tittle of this question is "Find text in string with C#", so this is a good solution for that. In my case this is what i was looking for. Regards – César León Nov 22 '22 at 16:51
  • @CésarLeón - to "find" something is to discover *where* it is. All this tells you is whether or not the text occurs in the string. It gives you no idea where. – Paul Sinclair Apr 04 '23 at 14:06
29

You could use Regex:

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);
}
Sergii Zhevzhyk
  • 4,074
  • 22
  • 28
MichelZ
  • 4,214
  • 5
  • 30
  • 35
10
 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);
Kevin DiTraglia
  • 25,746
  • 19
  • 92
  • 138
5

Here's my function using Oscar Jara's function as a 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;
}

This version does at most two searches of the text. It avoids an exception thrown by Oscar's version when searching for an end string that only occurs before the start string, i.e., getBetween(text, "my", "and");.

Usage is the same:

string text = "This is an example string and my data is here";
string data = getBetween(text, "my", "is");
Johnny Cee
  • 389
  • 6
  • 15
4

You can do it compactly like this:

string abc = abc.Replace(abc.Substring(abc.IndexOf("me"), (abc.IndexOf("is", abc.IndexOf("me")) + 1) - abc.IndexOf("size")), string.Empty);
Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
Prashant
  • 41
  • 1
4

Except for @Prashant's answer, the above answers have been answered incorrectly. Where is the "replace" feature of the answer? The OP asked, "After that, I'd like to create a new string between that and something else".

Based on @Oscar's excellent response, I have expanded his function to be a "Search And Replace" function in one.

I think @Prashant's answer should have been the accepted answer by the OP, as it does a replace.

Anyway, I've called my variant - 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;
    }
}
Fandango68
  • 4,461
  • 4
  • 39
  • 74
3
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();
    }
RAMESH
  • 31
  • 1
3
  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);


        }
Reza Taibur
  • 263
  • 3
  • 10
3
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();
        }


    }












        }
Debendra Dash
  • 5,334
  • 46
  • 38
2

This is the correct way to replace a portion of text inside a string (based upon the getBetween method by Oscar Jara):

public static string ReplaceTextBetween(string strSource, string strStart, string strEnd, string strReplace)
    {
        int Start, End, strSourceEnd;
        if (strSource.Contains(strStart) && strSource.Contains(strEnd))
        {
            Start = strSource.IndexOf(strStart, 0) + strStart.Length;
            End = strSource.IndexOf(strEnd, Start);
            strSourceEnd = strSource.Length - 1;

            string strToReplace = strSource.Substring(Start, End - Start);
            string newString = string.Concat(strSource.Substring(0, Start), strReplace, strSource.Substring(Start + strToReplace.Length, strSourceEnd - Start));
            return newString;
        }
        else
        {
            return string.Empty;
        }
    }

The string.Concat concatenates 3 strings:

  1. The string source portion before the string to replace found - strSource.Substring(0, Start)
  2. The replacing string - strReplace
  3. The string source portion after the string to replace found - strSource.Substring(Start + strToReplace.Length, strSourceEnd - Start)
1

Simply add this code:

if (string.Contains("search_text")) { MessageBox.Show("Message."); }

Rokonz Zaz
  • 166
  • 1
  • 7
  • 2
    Welcome to StackOverflow! Please describe what your code does instead of just pasting it. By this future visitors with the same question can understand what they should do. – Hille Mar 05 '19 at 08:07
0

If you know that you always want the string between "my" and "is", then you can always perform the following:

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();
Sergii Zhevzhyk
  • 4,074
  • 22
  • 28
0

First find the index of text and then substring

        var ind = Directory.GetCurrentDirectory().ToString().IndexOf("TEXT To find");

        string productFolder = Directory.GetCurrentDirectory().ToString().Substring(0, ind);
Taran
  • 2,895
  • 25
  • 22
0

I have different approach on ReplaceTextBetween() function.

public static string ReplaceTextBetween(this string strSource, string strStart, string strEnd, string strReplace)
        {
            if (strSource.Contains(strStart) && strSource.Contains(strEnd))
            {
                var startIndex = strSource.IndexOf(strStart, 0) + strStart.Length;

                var endIndex = strSource.IndexOf(strEnd, startIndex);

                var strSourceLength = strSource.Length;

                var strToReplace = strSource.Substring(startIndex, endIndex - startIndex);

                var concatStart = startIndex + strToReplace.Length;

                var beforeReplaceStr = strSource.Substring(0, startIndex);

                var afterReplaceStr = strSource.Substring(concatStart, strSourceLength - endIndex);

                return string.Concat(beforeReplaceStr, strReplace, afterReplaceStr);
            }

            return strSource;
        }
009topersky
  • 101
  • 3
  • 4
0

Correct answer here without using any pre-defined method.

    static void WordContainsInString()
    {
        int f = 0;
        Console.WriteLine("Input the string");
        string str = Console.ReadLine();
        Console.WriteLine("Input the word to search");
        string word = Console.ReadLine();
        int l = str.Length;
        int c = word.Length;

        for (int i = 0; i < l; i++)
        {
            if (str[i] == word[0])
            {
                for (int K = i + 1, j = 1; j < c; j++, K++)
                {
                    if (str[K] == word[j])
                    {
                        f++;
                    }
                    else 
                    { 
                        f = 0; 
                    }
                }
            }
        }
        if (f == c - 1)
        {
            Console.WriteLine("matching");
        }
        else
        {
            Console.WriteLine("not found");
        }
        Console.ReadLine();
    }
Rahul Jha
  • 874
  • 1
  • 11
  • 28
0

for .net 6 can use next code

public static string? Crop(string? text, string? start, string? end = default)
{
    if (text == null) return null;

    string? result;

    var startIndex = string.IsNullOrEmpty(start) ? 0 : text.IndexOf(start);

    if (startIndex < 0) return null;

    startIndex += start?.Length ?? 0;

    if (string.IsNullOrEmpty(end))
    {
        result = text.Substring(startIndex);
    }
    else
    {
        var endIndex = text.IndexOf(end, startIndex);

        if (endIndex < 0) return null;

        result = text.Substring(startIndex, endIndex - startIndex);
    }

    return result;
}