user175084
user175084

Reputation: 4640

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 temp 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.

Upvotes: 1

Views: 12815

Answers (5)

configurator
configurator

Reputation: 41690

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.

Upvotes: 1

p.campbell
p.campbell

Reputation: 100657

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

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1503984

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.

Upvotes: 4

Oded
Oded

Reputation: 499382

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"

Upvotes: 0

Mark Pope
Mark Pope

Reputation: 11274

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

Upvotes: 0

Related Questions