c#我需要帮助将管道字符中的单词解析为字符串列表。
“您可以在办理入住前免费取消直到| 720 |。如果在办理入住前在| 720 |中取消,则需要支付| 407.74USD |。”
字符串列表应包含两个项目。 720和407.74美元。
谢谢
答案 0 :(得分:0)
private static IEnumerable<string> GetStringsBetweenDelimiters(string str, char delimiter)
{
int openingIndex = default; //index of the opening delimiter
int closingIndex = -1; //starts from -1 as otherwise it would not work for string
//starting with delimiter
while (true)
{
openingIndex = str.IndexOf(delimiter, closingIndex + 1);
//it has to be +1'd as otherwise it would return closingIndex
if (openingIndex < 0) yield break; //No more delimiters
closingIndex = str.IndexOf(delimiter, openingIndex + 1);
//+1'd for same reason as above
if (closingIndex < 0) //No closing delimiter
throw new InvalidOperationException("The given string has odd number of delimiters.");
//Might just break as well?
yield return str.Substring(openingIndex + 1, closingIndex - openingIndex - 1);
}
}
像GetStringsBetweenDelimiters(str, '|')
那样调用时,此方法仅返回两个管道字符之间的值。此方法相对于string.Split(delimiter)的优势在于,它不会分配不在竖线字符(You can cancel free of charge until
,before check-in. You’ll be charged
...)之间的不必要的子字符串,这可能会更简单使用。
测试:
foreach (string str in GetStringBetweenDelimiters(testStr, '|'))
{
Console.WriteLine(str);
}
打印
720
407.74USD
720