split string by indexOf

N

N9

Hi

Anyone who can help about split string.

string text = "History about a boy, who loves to play baseball with
his friends."

I like to find indexOf "play" and read the string 10 char left and 10
char right

The result: " loves to play baseball "

but my problem is, if I indexOf "his", it fail, because, " friends."
only had 9 char.

It's the same problem at the start of text.

anyone who can help ??

//N9
 
M

Marc Gravell

Smells like homework?

You need to adjust the ends if they go outside of the range...

int pre = 10, post = 10;
string text = "History about a boy, who loves to play baseball
with his friends.",
search = "play";
int index = text.IndexOf(search);
int start = index - pre, end = index + search.Length + post;
if (start < 0) start = 0;
if (end > text.Length) end = text.Length;
string subString = text.Substring(start, end - start);

Marc
 
J

Jon Skeet [C# MVP]

Smells like homework?

You need to adjust the ends if they go outside of the range...

int pre = 10, post = 10;
string text = "History about a boy, who loves to play baseball
with his friends.",
search = "play";
int index = text.IndexOf(search);
int start = index - pre, end = index + search.Length + post;
if (start < 0) start = 0;
if (end > text.Length) end = text.Length;
string subString = text.Substring(start, end - start);

An alternative to the last four lines:

int start = Math.Max(0, index-pre);
int end = Max.Min(text.Length, index+pre);
string subString = text.Substring(start, end-start);

Jon
 

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

Top