Reputation: 4520
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?
Upvotes: 24
Views: 105283
Reputation: 11
You guys.. You only need to create a new Function by yourself. Here, Use my code.
public string subsequence(string s, int start, int end) {
string startstring = s.Substring(start);
string endstring = s.Substring(end);
startstring = startstring.Replace(endstring, "");
return startstring;
}
Upvotes: 0
Reputation: 11
string s1 = "find a string between within a lengthy string";
string s2 = s1.IndexOf("between").ToString();
string output = s1.Substring(0, int.Parse(s2));
Console.WriteLine("string before between is : {0}", output);
Console.ReadKey();
Upvotes: 1
Reputation: 21742
You can simply calculate the length from the start and end
const string startText = "hello my friend";
var start = str.LastIndexOf(startText) + startText.Length;
var end = str.IndexOf("Goodbye my friend");
var length = end -start;
str.Substring(start,length);
Upvotes: 3
Reputation: 150108
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
.
Upvotes: 34
Reputation: 116108
you can also use Regex
string s = Regex.Match(yourinput,
@"hello my friend(.+)Goodbye my friend",
RegexOptions.Singleline)
.Groups[1].Value;
Upvotes: 14