[英]Reading a string from and to a certain character
我想知道是否可以讀取從x字符到y字符的某個n長度的字符串,而不必將其拆分成較小的部分。
我有以下字符串,用於AD CN=someName,OU=someGroup,OU=groups,DC=some,DC=domain,DC=com
的路徑,我希望能夠只讀取其中的someName
部分而不通過拆分=
或,
第一。 我該如何實現?
原因是,我不必像現在那樣進行組比較:
SearchResult t1 = search.FindOne();
foreach (string s in t1.Properties["memberof"])
{
foreach (string g in groups)
{
if (s.ToLower().Contains(g.ToLower()))
{
// do something
}
}
}
我寧願將if子句設為相等,但我不想總是將上述路徑/組分成一個數組兩次。 我怎么做?
對IndexOf
和Substring
使用簡單的字符串操作:
string s = "CN=someName,OU=someGroup,OU=groups,DC=some,DC=domain,DC=com";
const string prefix = "CN=";
int start = s.IndexOf(prefix);
if (start >= 0)
{
string value = s.Substring(start + prefix.Length, s.IndexOf(',', start) - prefix.Length);
Console.WriteLine(value);
}
請注意, 如果 CN=
條目是該行的最后一個,則此簡單示例將失敗(因為它沒有被逗號終止)。 不過,您可以通過查看第二個IndexOf
調用的返回值來首先進行檢查。
但是在這種情況下,無論如何, CN=
通常通常是第一件事。
如果要進行組比較,我將使用System.DirectoryServices.AccountManagement命名空間
PrincipalContext Context = new PrincipalContext(ContextType.Domain, "");
UserPrincipal Usr = UserPrincipal.FindByIdentity(Context, "User");
GroupPrincipal G = GroupPrincipal.FindByIdentity(Context, "Group");
if(Usr.IsMemberOf(G)) {
}
隨着Split
您可以檢查是否有任何給定的鍵等於搜索值。
var val = "CN=someName,OU=someGroup,OU=groups,DC=some,DC=domain,DC=com";
var prefix = "CN";
var searchValue = "someName";
var contains = val.Split(',').Any(value => value.Split('=')[0] == prefix && value.Split('=')[1] == searchValue);
嘗試檢查該值是否等於搜索值,也可以只返回該值。
var val = "CN=someName,OU=someGroup,OU=groups,DC=some,DC=domain,DC=com";
var prefix = "CN";
var foundValue = val.Split(',').FirstOrDefault(value => value.Split('=')[0] == prefix)?.Split('=')[1];
盡管您說過您不想使用它,但我仍然使用Split
,因為我認為它可以很好地用作襯板。
您可以使用String.IndexOf
查找正確的偏移量,然后使用String.SubString
讀取所需的零件。
const string input = "CN=someName,OU=someGroup,OU=groups,DC=some,DC=domain,DC=com";
const string start = "CN=";
const string stop = ",";
int startIndex = input.IndexOf(start, 0);
int stopIndex = input.IndexOf(stop, startIndex);
var extracted = input.Substring(startIndex + start.Length, stopIndex - startIndex - start.Length);
Console.WriteLine(extracted);
PS:也許還要看看。 是否有一個.NET類可以從LDAP中解析CN =字符串? 為您的特殊用例!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.