C# 从字符串中提取子字符串

C# 从字符串中提取子字符串,c#,c#-4.0,C#,C# 4.0,从指定字符串中提取子字符串的最佳方法是什么 我的主字符串是 string str = "<ABCMSG><t>ACK</t><t>AAA0</t><t>BBB1</t></ABCMSG>"; string str=“ACKAAA0BBB1”; 其中,值AAA0和BBB1是从某处收集的动态值 我需要在这里提取AAA0和BBB1 请建议我,如果有任何功能或优化的方式来做到这一点 谢谢大家! 这绝对是

从指定字符串中提取子字符串的最佳方法是什么

我的主字符串是

string str = "<ABCMSG><t>ACK</t><t>AAA0</t><t>BBB1</t></ABCMSG>"; 
string str=“ACKAAA0BBB1”;
其中,值AAA0和BBB1是从某处收集的动态值

我需要在这里提取AAA0和BBB1

请建议我,如果有任何功能或优化的方式来做到这一点


谢谢大家!

这绝对是低效的,但它能满足你的要求。它假设周围XML的布局是不变的

var foo = "<ABCMSG><t>ACK</t><t>AAA0</t><t>BBB1</t></ABCMSG>"; 
var ary = XDocument.Parse(foo).Root.Elements().ToArray();

// ary[1].Value -> AAA0
// ary[2].Value -> BBB1
var foo=“ACKAAA0BBB1”;
var ary=XDocument.Parse(foo.Root.Elements().ToArray();
//ary[1]。值->AAA0
//ary[2]。值->BBB1

使用XmlDocument的方法

void Main()
{
    string str = "<ABCMSG><t>ACK</t><t>AAA0</t><t>BBB1</t></ABCMSG>"; 
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(str);
    var t = doc.GetElementsByTagName("t");
    Console.WriteLine(t[1].InnerText);
    Console.WriteLine(t[2].InnerText);
}
void Main()
{
string str=“ACKAAA0BBB1”;
XmlDocument doc=新的XmlDocument();
doc.LoadXml(str);
var t=doc.GetElementsByTagName(“t”);
Console.WriteLine(t[1].InnerText);
Console.WriteLine(t[2].InnerText);
}

没有必要发布两次,您已经在这里询问过了,这取决于复杂性。如果您正在查看完整的XML或HTML,那么一个好的XML或HTML解析器就很好了。如果每个字符串都像你指出的那样简单,那么我就来看看正则表达式