我有一些关于“从两个字符串之间找到特定字符串并进入列表”的问题。
我有一个这样的字符串:
-begin-
code:[264]
Name:[1]
Name:[2]
Name:[3]
-end-
code:[264]
Name:[1]
Name:[4]
code:[264]
Name:[6]
-begin-
Name:[6]
code:[264]
Name:[7]
Name:[8]
Name:[1]
-end-
我想将“-begin-”到“-end-”之间的字符串“Name:”拆分成List,如下所示,
list<1>
Name:[1]
Name:[2]
Name:[3]
list<2>
Name:[6]
Name:[7]
Name:[8]
Name:[1]
现在我只能将“-begin-”到“-end-”之间的文本拆分成列表。
int first = 0;
int last = 0;
int number = 0;
int start = 0;
do {
first = text.IndexOf("-begin-", start);
last = text.IndexOf("-begin-", first + 1);
if (first >= 0 && last >= 0)
{
number = (last - first);
AVPline.Add(text.Substring(first,number).Trim());
start = last + 1;
}
} while (position > 0);
我不知道在“-begin-”到“-end - ”之间拆分文本后拆分字符串“Name:”。
有人可以帮助我。
非常感谢你。
答案 0 :(得分:1)
String.Split会将字符串解析为数组子字符串。然后你处理子串。
string[] parseStr = text.Split('\n');
答案 1 :(得分:1)
您可以使用枚举器和yield return
来实现更清晰,可维护的代码:
首先,让我们获得正确的签名。您需要从输入字符串创建列表集合:public static IEnumerable<IList<string>> ProcessText(string input)
看起来正确。
现在,让我们的生活更轻松。首先,让我们将输入字符串分成行:
var lines = input.Split(new[] { Environment.NewLine });
现在,让我们遍历这些行,但不要使用foreach
来执行此操作。让我们变得有点脏,并直接使用枚举器,原因很明显:
using (var enumerator = lines.GetEnumerator())
{
while (enumerator.MoveNext()
{
}
}
好的,现在我们只需找到每个子列表的开头并相应地构建它。多么容易:
while (enumerator.MoveNext()
{
if (enumerator.Current == "-begin-"
yield return createSubList(enumerator).ToList();
}
现在你明白为什么我直接使用Enumerator了。这样我就可以调用另一种方法轻松跟踪输入文本中的位置:
static IEnumerable<string> createSubList(IEnumerator<string> enumerator)
{
while (enumerator.MoveNext()
{
if (enumerator.Current == "-end-")
{
yield break;
}
if (!enumerator.Current.StartsWith(...whatever strings you want to ignore))
{
yield return enumerator.Current;
}
}
}
我们已经完成了!让我们把它们放在一起:
public IEnumerable<IList<string>> ProcessText(string input)
{
var lines = input.Split(new[] { Environment.NewLine });
using (var enumerator = lines.GetEnumerator())
{
while (enumerator.MoveNext()
{
if (enumerator.Current == "-begin-"
yield return createSubList(enumerator).ToList();
}
}
}
private static IEnumerable<string> createSubList(IEnumerator<string> enumerator)
{
while (enumerator.MoveNext()
{
if (enumerator.Current == "-end-")
{
yield break;
}
if (!enumerator.Current.StartsWith(...whatever strings you want to ignore))
{
yield return enumerator.Current;
}
}
}
答案 2 :(得分:0)
您的尝试距离工作解决方案并不太远 我手边只有手机,所以我不能给你测试代码。但这是我的建议:
-begin-
和-end-
-begin-
和-end-
之间获取所需数据,并在内部(嵌套)循环中处理它嵌套循环:
Name
和结束]
。嵌套循环后,仍在外循环中:
外环结束。
请记住为外循环使用有效条件。在您的示例中,您从未设置“位置”。