如果我有一系列具有此基本格式的字符串:
"[id value]"//id and value are space delimited. id will never have spaces
然后它们可以像这样嵌套:
[a]
[a [b value]]
[a [b [c [value]]]
因此每个项目可以有 0 或 1 个值条目。
解析这种格式的最佳方法是什么?我只使用 string.Split() 或 string.IndexOf() 这样的东西还是有更好的方法?
最佳答案
split和indexof方法没有任何问题,它们是为了字符串解析而存在的。 以下是您的案例的示例:
string str = "[a [b [c [d value]]]]";
while (str.Trim().Length > 0)
{
int start = str.LastIndexOf('[');
int end = str.IndexOf(']');
string s = str.Substring(start +1, end - (start+1)).Trim();
string[] pair = s.Split(' ');// this is what you are looking for. its length will be 2 if it has a value
str = str.Remove(start, (end + 1)- start);
}
关于c# - 解析 C Sharp 中的嵌套文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3912419/