Created
January 13, 2017 21:07
-
-
Save sachintha81/bd0b138885590970afc8c63f35f58cba to your computer and use it in GitHub Desktop.
WPF + C# Extract a Substring from a String between two specified Parts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Windows; | |
using System.Collections.ObjectModel; | |
using System.IO; | |
using System.Linq; | |
using System.Windows.Input; | |
using System.Xml.Linq; | |
namespace StringProgram | |
{ | |
public partial class StringProgram : Window | |
{ | |
// Extracts a substring from 'originalStr', which lies between 'beginStr' and 'endStr'. | |
// 'includeBeginAndEnd' specifies whether 'beginStr' and 'endStr' are incldued in the extracted string. | |
public static bool GetSubstringByString(string beginStr, string endStr, string originalStr, bool includeBeginAndEnd, out string substring, out string msg) | |
{ | |
bool ret = true; | |
substring = string.Empty; | |
msg = string.Empty; | |
if (!originalStr.Contains(beginStr) || !originalStr.Contains(endStr)) | |
{ | |
msg = ERR_STR_DOES_NOT_CONTAIN; | |
ret = false; | |
} | |
else | |
{ | |
if (originalStr.IndexOf(beginStr) >= originalStr.IndexOf(endStr)) | |
{ | |
msg = ERR_STR_END_BEFORE_BEGIN; | |
ret = false; | |
} | |
else | |
{ | |
int beginIndex = 0; | |
int len = 0; | |
if (includeBeginAndEnd) | |
{ | |
beginIndex = originalStr.IndexOf(beginStr); | |
len = originalStr.IndexOf(endStr) - originalStr.IndexOf(beginStr) + endStr.Length; | |
} | |
else | |
{ | |
beginIndex = originalStr.IndexOf(beginStr) + beginStr.Length; | |
len = originalStr.IndexOf(endStr) - originalStr.IndexOf(beginStr) - beginStr.Length; | |
} | |
substring = originalStr.Substring(beginIndex, len); | |
} | |
} | |
return ret; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on an answer here:
http://stackoverflow.com/a/4822334/302248