如何得到字符串的一部分

本文关键字:一部分 字符串 何得 | 更新日期: 2023-09-27 17:53:52

我有一个字符串如:

string a =  "OU=QALevel1,DC=CopTest,DC=copiun2,DC=com";

现在我想让我的temp字符串的值为

 tempString = "DC=CopTest,DC=copiun2,DC=com"

我需要从字符串中删除所有出现的OU值对。这些总是首先出现在字符串中。

如何得到字符串的一部分

嗯,这取决于你希望是什么理由。如果你想要第一个逗号之后的所有内容,你可以使用:

int comma = a.IndexOf(',');
if (comma != -1)
{
    string tempString = a.Substring(comma + 1);
    // Use tempString
}
else
{
    // Deal with there not being any commas
}

如果您不希望这样分割字符串,请给出您需要做的更多信息。

编辑:如果您需要"第一个逗号后面跟着DC=",您可以将第一行更改为:

int comma = a.IndexOf(",DC=");

再说一遍,如果你需要其他东西,请更具体地说明你想做什么。

您可以使用LINQ来帮助:

string foo = "OU=SupportSubLevel3,OU=SupportLevel1,DC=CopTest,DC=copiun2,DC=com";
string sub = string.Join(",", 
                         foo.Split(',')
                            .Where(x => x.StartsWith("DC")));
Console.WriteLine(sub);
  • 用逗号
  • 将字符串分割成一个数组
  • 只取DC
  • 开头的
  • 放回字符串中,用逗号分隔

我怀疑这里实际需要的是所有域组件。你甚至可能想把它们分开。这个示例将支持任何DN语法,并从中提取DC:

string a = "OU=QALevel1,DC=CopTest,DC=copiun2,DC=com";
// Separate to parts
string[] parts = a.Split(',');
// Select the relevant parts
IEnumerable<string> dcs = parts.Where(part => part.StartsWith("DC="));
// Join them again
string result = string.Join(",", dcs);

注意,您将获得dcs(所有DC部件的枚举)和result(您请求的字符串)。但最重要的是,这段代码是有意义的—当您看到它时,您确切地知道它将做什么—返回一个字符串,其中包含原始字符串的所有DC=*部分的列表,删除任何非dc部分。

您将需要为此使用Substring函数,但是如何使用它取决于您的标准。例如,您可以这样做:

tempString = a.Substring(12);

如果你能告诉我们你的标准,那将非常有用

假设OU总是在其他值对之前,这将获得最后一个OU值之后的所有字符串:

string a =  "OU=QALevel1,DC=CopTest,DC=copiun2,DC=com";
string res = a.Substring(a.IndexOf(',', a.LastIndexOf("OU=")) + 1);
// res = "DC=CopTest,DC=copiun2,DC=com"