提取两个字符串之间的所有字符串 [英] Extract all strings between two strings
本文介绍了提取两个字符串之间的所有字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想开发将匹配两个字符串之间的所有字符串的方法:
我试过,但它只返回的第一个匹配:
字符串ExtractString(字符串s,串开始,串完)
{
//您应该检查在现实世界code错误,不再赘述 INT的startIndex = s.IndexOf(开始)+ start.Length;
INT endIndex的= s.IndexOf(结束,则startIndex);
返回s.Substring(的startIndex,endIndex的 - 的startIndex);
}
让我们假设我们有这个字符串
字符串文本=A1FIRSTSTRINGA2A1SECONDSTRINGA2akslakhflkshdflhksdfA1THIRDSTRINGA2
我想一个C#函数执行以下操作:
公开名单<串GT; ExtractFromString(文本字符串,字符串开始,字符串完)
{
清单<串GT;匹配=新的List<串GT;();
。
。
。
返回匹配的;
}
//使用示例ExtractFromString(A1FIRSTSTRINGA2A1SECONDSTRINGA2akslakhflkshdflhksdfA1THIRDSTRINGA2,A1,A2) // 将返回 :
// FIRSTSTRING
// SECONDSTRING
// THIRDSTRING
感谢您的帮助!
解决方案
私有静态列表<串GT; ExtractFromString(
字符串文本字符串startString,串endString)
{
清单<串GT;匹配=新的List<串GT;();
INT indexStart = 0,indexEnd = 0;
BOOL退出= FALSE;
而(!出口)
{
indexStart = text.IndexOf(startString);
indexEnd = text.IndexOf(endString);
如果(indexStart = -1&安培;!&安培;!indexEnd = -1)
{
matched.Add(text.Substring(indexStart + startString.Length,
indexEnd - indexStart - startString.Length));
文字= text.Substring(indexEnd + endString.Length);
}
其他
退出= TRUE;
}
返回匹配的;
}
I'm trying to develop a method that will match all strings between two strings:
I've tried this but it returns only the first match:
string ExtractString(string s, string start,string end)
{
// You should check for errors in real-world code, omitted for brevity
int startIndex = s.IndexOf(start) + start.Length;
int endIndex = s.IndexOf(end, startIndex);
return s.Substring(startIndex, endIndex - startIndex);
}
Let's suppose we have this string
String Text = "A1FIRSTSTRINGA2A1SECONDSTRINGA2akslakhflkshdflhksdfA1THIRDSTRINGA2"
I would like a c# function doing the following :
public List<string> ExtractFromString(String Text,String Start, String End)
{
List<string> Matched = new List<string>();
.
.
.
return Matched;
}
// Example of use
ExtractFromString("A1FIRSTSTRINGA2A1SECONDSTRINGA2akslakhflkshdflhksdfA1THIRDSTRINGA2","A1","A2")
// Will return :
// FIRSTSTRING
// SECONDSTRING
// THIRDSTRING
Thank you for your help !
解决方案
private static List<string> ExtractFromString(
string text, string startString, string endString)
{
List<string> matched = new List<string>();
int indexStart = 0, indexEnd=0;
bool exit = false;
while(!exit)
{
indexStart = text.IndexOf(startString);
indexEnd = text.IndexOf(endString);
if (indexStart != -1 && indexEnd != -1)
{
matched.Add(text.Substring(indexStart + startString.Length,
indexEnd - indexStart - startString.Length));
text = text.Substring(indexEnd + endString.Length);
}
else
exit = true;
}
return matched;
}
这篇关于提取两个字符串之间的所有字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文