Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get string between strings in c#

Tags:

string

c#

I am trying to get string between same strings:

The texts starts here ** Get This String ** Some other text ongoing here.....

I am wondering how to get the string between stars. Should I should use some regex or other functions?

like image 250
birdcage Avatar asked Apr 07 '17 08:04

birdcage


People also ask

How do I extract a string between two characters?

To extract part string between two different characters, you can do as this: Select a cell which you will place the result, type this formula =MID(LEFT(A1,FIND(">",A1)-1),FIND("<",A1)+1,LEN(A1)), and press Enter key. Note: A1 is the text cell, > and < are the two characters you want to extract string between.

How to check equality of two string in C?

C strcmp() The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.

How to get input for a string in C?

We can take string input in C using scanf(“%s”, str).


2 Answers

You can try Split:

  string source = 
    "The texts starts here** Get This String **Some other text ongoing here.....";

  // 3: we need 3 chunks and we'll take the middle (1) one  
  string result = source.Split(new string[] { "**" }, 3, StringSplitOptions.None)[1];
like image 179
Dmitry Bychenko Avatar answered Sep 25 '22 06:09

Dmitry Bychenko


You can use IndexOf to do the same without regular expressions.
This one will return the first occurence of string between two "**" with trimed whitespaces. It also has checks of non-existence of a string which matches this condition.

public string FindTextBetween(string text, string left, string right)
{
    // TODO: Validate input arguments

    int beginIndex = text.IndexOf(left); // find occurence of left delimiter
    if (beginIndex == -1)
        return string.Empty; // or throw exception?

    beginIndex += left.Length;

    int endIndex = text.IndexOf(right, beginIndex); // find occurence of right delimiter
    if (endIndex == -1)
        return string.Empty; // or throw exception?

    return text.Substring(beginIndex, endIndex - beginIndex).Trim(); 
}    

string str = "The texts starts here ** Get This String ** Some other text ongoing here.....";
string result = FindTextBetween(str, "**", "**");

I usually prefer to not use regex whenever possible.

like image 27
Yeldar Kurmangaliyev Avatar answered Sep 24 '22 06:09

Yeldar Kurmangaliyev