How do I extract part of a string in C#

Posted on 2009-04-21
Last Modified: 2012-06-21
I have some data in this format "bnSet0_0", "bnSet0_1",

I try to extract the '0' right after "bnSet" and before '_'

Question by:xewoox
    LVL 22

    Expert Comment

    if will always, ALWAYS be in that format

    String val = "bnSet0_0";
                val = val.Substring(val.IndexOf('_') - 1, 1);
    LVL 16

    Accepted Solution

    if the number to extract is single digit only then the answer given by p_davis is correct.

    Else, if the number can be of multiple digits here is the solution

    string str = "bnSet12_1"
    string startPos = str.IndexOf("bnSet") + 5;
    string endPos = str.IndexOf("_");
    string result = str.SubString(startPos, endPos - startPos);

    Author Comment

    There is some problem with  code from CuteBug

    string str = "bnSet12_1";
    int startPos = str.IndexOf("bnSet") + 5;
    int endPos = str.IndexOf("_");
    string result = str.Substring(startPos, endPos - startPos);

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to improve team productivity

    Quip adds documents, spreadsheets, and tasklists to your Slack experience
    - Elevate ideas to Quip docs
    - Share Quip docs in Slack
    - Get notified of changes to your docs
    - Available on iOS/Android/Desktop/Web
    - Online/Offline

    Bit flags and bit flag manipulation is perhaps one of the most underrated strategies in programming, likely because most programmers developing in high-level languages rely too much on the high-level features, and forget about the low-level ones. Th…
    Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
    Need more eyes on your posted question? Go ahead and follow the quick steps in this video to learn how to Request Attention to your question. *Log into your Experts Exchange account *Find the question you want to Request Attention for *Go to the e…
    Here's a very brief overview of the methods PRTG Network Monitor ( offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

    779 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now