C# 如何通过位置和分隔符提取字符串的子字符串
如何将子字符串与字符串分开 就像我有绳子一样C# 如何通过位置和分隔符提取字符串的子字符串,c#,.net,winforms,string,C#,.net,Winforms,String,如何将子字符串与字符串分开 就像我有绳子一样 String mainString="///Trade Time///Trade Number///Amount Rs.///"; 现在我有了另一根弦 String subString="Amount" 然后我想通过名为substring的第二个字符串来提取子字符串Amount Rs.,而不是通过任何其他方法,但它应该通过两个参数来提取,例如第一个参数是我没有Amount string的索引号,第二个参数是直到下一个字符串//。这应该可以解决您的
String mainString="///Trade Time///Trade Number///Amount Rs.///";
现在我有了另一根弦
String subString="Amount"
然后我想通过名为substring的第二个字符串来提取子字符串
Amount Rs.
,而不是通过任何其他方法,但它应该通过两个参数来提取,例如第一个参数是我没有Amount string的索引号,第二个参数是直到下一个字符串//。这应该可以解决您的问题,我相信:
mainString.substring(mainString.IndexOf("Amount Rs. "), "///")
其中,mainString.IndexOf(“Amount Rs.”)是起始索引
&“///”
是结束索引。首先获取子字符串的索引:
int startIndex = mainString.IndexOf(subString);
然后获取以下斜杠的索引:
int endIndex = mainString.IndexOf("///", startIndex);
然后可以获得所需的子字符串:
string amountString = mainString.Substring(startIndex, endIndex - startIndex);
string str=Regex.Match(“///(?[^/]*?”+子字符串+“[^/]*?)//”)。组[“字符串”]。值;
应该使用String.Format
,但是@String中{x}
的确切用法我记不得了(你需要将{}
加倍吗?)
注意:这假设您不期望任何/
,因此可以稍作改进。作为对@Guffa答案的补充,您可以从中使用扩展方法:
注意:没有验证来确保提供的索引在字符串的边界内
您已经在第一个字符串文本之前放置了@,因此它将查找\/\/\/
而不是//
。此外,\/
不是有效的转义序列。您应该对放入正则表达式中的子字符串
值使用Regex.Escape
方法,以使其对任何值都是安全的。
string str = Regex.Match("///(?<String>[^/]*?" + subString + "[^/]*?)///").Groups["String"].Value;
public static class StringExtensions
{
public static string SubstringBetweenIndexes(string value, int startIndex, int endIndex)
{
return value.Substring(startIndex, endIndex - startIndex);
}
}