Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

c# - Extract part of a string between point A and B

I am trying to extract something from an email. The general format of the email will always be:

blablablablabllabla hello my friend.

[what I want]

Goodbye my friend blablablabla

Now I did:

                    string.LastIndexOf("hello my friend");
                    string.IndexOf("Goodbye my friend");

This will give me a point before it starts, and a point after it starts. What method can I use for this? I found:

String.Substring(Int32, Int32)

But this only takes the start position.

What can I use?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Substring takes the start index (zero-based) and the number of characters you want to copy.

You'll need to do some math, like this:

string email = "Bla bla hello my friend THIS IS THE STUFF I WANTGoodbye my friend";
int startPos = email.LastIndexOf("hello my friend") + "hello my friend".Length + 1;
int length = email.IndexOf("Goodbye my friend") - startPos;
string sub = email.Substring(startPos, length);

You probably want to put the string constants in a const string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...