-1

I have a problem about trimming below word in C#

For example, I got a string = "StackLevelTwoItem" and I need to pull the "Two" or "Three" out of this string.

StackLevelTwoItem -> I should get "Two"
StackLevelThreeItem -> I should get "Three"

... and so on ...

Can anybody help?

Thank you

ms_jordan
  • 151
  • 1
  • 1
  • 8

3 Answers3

2

For the two examples given:

const string prefix = "StackLevel";
const string suffix = "Item";

public static string GetCentralPart(string str)
{
    if (str == null)
    {
        return str;
    }

    if (!str.StartsWith(prefix) || !str.EndsWith(suffix))
    {
        return str;
    }

    return str.Substring(prefix.Length, str.Length - prefix.Length - suffix.Length);
}

Use:

string str = "StackLevelThreeItem";
string centralPart = GetCentralPart(str);

The code is quite linear... The only interesting points are the use of some const string for the prefix/suffix, the use of StartsWith/EndsWith to check that the string really has the prefix/suffix, and how the Substring length is calculated.

xanatos
  • 109,618
  • 12
  • 197
  • 280
0

i would use RegEx for this Case

string Result = Regex.Match("StackLevelOneItem", @"(?<=StackLevel)[\w]*(?=Item)").Value; 
fubo
  • 44,811
  • 17
  • 103
  • 137
  • I tried this solution and it worked perfect. Thank you so much fubo, Anton Kedrov and xanatos for genuinely being helpful. Also, I would like to comment about "Soner Gönül" marking my question as duplicate adn addressing to a totally irrelevant link. The link he point is about pulling a word from a big sentence. My case here is different. Hope he can see this comment and rewind what he did was wrong! – ms_jordan May 26 '15 at 13:49
  • @ms_jordan - great! if you like, you can accept my answer :) – fubo May 29 '15 at 05:59
0

Here is an example using Regex.

static void Main(string[] args)
{
    var l2 = GetLevel("StackLevelTwoItem");     // returns "Two"
    var l3 = GetLevel("StackLevelThreeItem");   // returns "Three"
    var l1 = GetLevel("StackLvlOneItem");       // returns empty string
}

static string GetLevel(string input)
{
    var pattern = "StackLevel(.*)Item";
    var match = Regex.Match(input, pattern);

    if (match.Groups[1].Success)
        return match.Groups[1].Value;
    else
        return String.Empty;
}
Anton Kedrov
  • 1,767
  • 2
  • 13
  • 20