Extract String between two string in C#?


Hello, I want simple and easy solution to extract or get string between two strings in C#, so for example I have string "Hello World, I am .NET developer", I need output as "I am" only.

How can i do it in simple and fast way? Thanks


Asked by:- Vinnu
1
: 347 At:- 5/27/2022 8:01:53 AM
C# string between strings







1 Answers
profileImage Answered by:- vikas_jk

Since, we need string between "," and "." so we already know from where to extract string, we can use .substring()

		string str = "Hello World, I am .NET developer";
		int startPoint = str.IndexOf(",") + ",".Length;
		int endPOint = str.LastIndexOf(".");

		String result = str.Substring(startPoint, endPOint - startPoint);
		Console.WriteLine(result);

and this will give output

 I am

Using Regex

        string str = "Hello World, I am .NET developer";
        var match = Regex.Match(str, @"(\s([a-zA-Z]+\s)+)").Groups[1].Value;


		Console.WriteLine(match);

Hope it helps, Thanks

2
At:- 5/27/2022 8:31:44 AM
Thanks substring method looks good to me. 0
By : Vinnu - at :- 5/27/2022 8:35:09 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly