C# 提取 A 点和 B 点之间的部分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9505400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extract part of a string between point A and B
提问by TheGateKeeper
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?
我可以使用什么?
采纳答案by Eric J.
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.
您可能想将字符串常量放在const string.
回答by Alexander Corwin
try myStr.substring(start,end);
尝试 myStr.substring(start,end);
回答by L.B
you can also use Regex
你也可以使用正则表达式
string s = Regex.Match(yourinput,
@"hello my friend(.+)Goodbye my friend",
RegexOptions.Singleline)
.Groups[1].Value;
回答by Rune FS
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);
回答by pravi.net
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();

