开发者

how to get one part of the string

I have a string eg.

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

now i want my tem开发者_运维技巧p string to have the value

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

I need to remove all occurrences of the OU value pairs from the strings. These always appear first in the string.


Well, it depends on what grounds you want it to be that. If you want everything after the first comma, you could use:

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

If that's not how you want to split the string, please give more information about what you need to do.

EDIT: If you need "the first comma followed by DC=" you can change the first line to:

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

Again, if you need something else, please be much more specific about what you're trying to do.


You could use LINQ to help:

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);
  • split the string into an array, on the commas
  • take only those starting with DC
  • put back into a string, separate each with a comma


I suspect what you actually need here is all the domain components. You might even want to split them. This example will support any DN syntax, and extract the DC's from it:

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);

Note that you get both dcs - an enumeration of all the DC parts, and result - the string you requested. But most importantly, this code makes sense - when you see it, you know exactly what it will do - return a string with a list of all the DC=* parts of the original string, removing any non-DC parts.


You will need to use the Substring function for this, but how you use it depends on your criteria. For example, you could just do this:

tempString = a.Substring(12);

If you could let us know you're criteria that'd be very useful


Assuming the OU is always before the rest of the value pairs, this will get you all of the string following the last OU value:

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"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜