Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...