How do I extract part of a string in C#

Posted on 2009-04-21
Medium Priority
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

ID: 24199977
if will always, ALWAYS be in that format

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

Accepted Solution

CuteBug earned 1500 total points
ID: 24200551
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

ID: 24201018
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);

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
Suggested Courses

831 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