get an subset of a string

  • Thread starter Thread starter authorking
  • Start date Start date
A

authorking

How can I get a subset of a string by define the start and end charactor.
 
authorking said:
How can I get a subset of a string by define the start and end charactor.

string sub = original.Substring (start, end-start);
 
Hi Authorking,

You use String.Substring(startp osition, number of characters to read)
or any of the overloads

Some samples:

string s = "Hello World";

string s1 = s.Substring(0, 5); // s1 == "Hello"
string s2 = s.Substring(6, 5); // s2 == "World"
string s3 = s.Substring(6); // == "World"
string s4 = s.Substring(s1.Length + " ".Length, s.Length - (s1.Length + " ".Length)); // == "World"

int startchar = 3;
int endchar = 7;

string s5 = s.Substring(startchar, endchar - startchar); // == "lo W"

You may need to adjust the position values if you consider the first character to be 1 or want to include character 7.
 
Hi,

Are you refering to start and end index?
or you want to get a substring in some other way, like getting from the
first "start char" up to the first "end char"
if your case is the first see jon's post
if the latter you will need first the first index of each char ( or the last
depending of your need ) for this you use IndexOf or LastIndexOf and then
SubString()

Cheers,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top