Skip to content

Instantly share code, notes, and snippets.

@sachintha81
Created January 13, 2017 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sachintha81/bd0b138885590970afc8c63f35f58cba to your computer and use it in GitHub Desktop.
Save sachintha81/bd0b138885590970afc8c63f35f58cba to your computer and use it in GitHub Desktop.
WPF + C# Extract a Substring from a String between two specified Parts
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;
}
}
}
@sachintha81
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment