Home >Backend Development >C++ >How to Extract a Substring Between Two Delimiters in C#?

How to Extract a Substring Between Two Delimiters in C#?

Linda Hamilton
Linda HamiltonOriginal
2025-01-23 00:46:35825browse

How to Extract a Substring Between Two Delimiters in C#?

Extract substrings between delimiters from a string

Suppose there is a string, such as "super example of string key : text I want to keep - end of my string", we need to extract the substring between "key : " and " -". Regular expressions are one possible solution, but there are other ways.

One way is to use a combination of IndexOf and Substring methods to extract substrings. The starting position (pFrom) is determined by finding the index of "key: " and adding its length. End position (pTo) Calculates the length of the substring by finding the last occurrence of "-" and subtracting it from pFrom.

Using this approach, the following code snippet demonstrates how to separate the desired substring:

<code class="language-csharp">string St = "super exemple of string key : text I want to keep - end of my string";

int pFrom = St.IndexOf("key : ") + "key : ".Length;
int pTo = St.LastIndexOf(" - ");

string result = St.Substring(pFrom, pTo - pFrom);</code>

Executing this code will get the desired substring "text I want to keep".

The above is the detailed content of How to Extract a Substring Between Two Delimiters in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn