How to count of sub-string occurrences?
本问题已经有最佳答案,请猛点这里访问。
假设我有这样一根绳子:
1 | MyString ="OU=Level3,OU=Level2,OU=Level1,DC=domain,DC=com"; |
然后我想知道在这个字符串中出现子字符串"ou="的次数。对于单字符,可能有如下内容:
1 | int count = MyString.Split("OU=").Length - 1; |
但
另外,如何找到n个事件的位置?例如,第二个
如何解决这个问题?
1 | Regex.Matches(input,"OU=").Count |
你可以找到所有的事件需要一个和他们的位置与
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | string MyString ="OU=Level3,OU=Level2,OU=Level1,DC=domain,DC=com"; string stringToFind ="OU="; List<int> positions = new List<int>(); int pos = 0; while ((pos < MyString.Length) && (pos = MyString.IndexOf(stringToFind, pos)) != -1) { positions.Add(pos); pos += stringToFind.Length(); } Console.WriteLine("{0} occurrences", positions.Count); foreach (var p in positions) { Console.WriteLine(p); } |
你可以得到相同的结果,从正则表达式:
1 2 3 4 5 6 | var matches = Regex.Matches(MyString,"OU="); Console.WriteLine("{0} occurrences", matches.Count); foreach (var m in matches) { Console.WriteLine(m.Index); } |
原发性差异:
- 在使用短码
- 该代码集和多allocates的正则表达式的字符串。
- 该指数代码可以立即书面输出的位置,而不创建一个集合。
- 这是有可能的,在隔离的正则表达式的代码将更快,但如果用许多时报联合字符串分配的开销可能导致非常高的负载在垃圾收集器。
这是我在网上写的东西,才有可能经常使用,我会去与正则表达式的解决方案。如果我是把它对图书馆使用的是很多东西,我会去的指标可能的解决方案。
(Clippy模式:在线)
你看起来像你是一个LDAP查询解析。
解析:你喜欢它
- 手动?"splittingandparsing goto"
- automagically Win32调用路径?"Win32路径PInvoke使用goto语句"
(Clippy -模式)
"splittingandparsing":
1 2 3 4 5 6 7 8 9 10 11 | var MyString ="OU=Level3,OU=Level2,OU=Level1,DC=domain,DC=com"; var chunksAsKvps = MyString .Split(',') .Select(chunk => { var bits = chunk.Split('='); return new KeyValuePair<string,string>(bits[0], bits[1]); }); var allOUs = chunksAsKvps .Where(kvp => kvp.Key.Equals("OU", StringComparison.OrdinalIgnoreCase)); |
"使用Win32路径PInvoke":
用法:
1 2 3 | var parsedDn = Win32LDAP.ParseDN(str); var allOUs2 = parsedDn .Where(dn => dn.Key.Equals("OU", StringComparison.OrdinalIgnoreCase)); |
实用程序代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 | // I don't remember where I got this from, honestly...I *think* it came // from another SO user long ago, but those details I've lost to history... public class Win32LDAP { #region Constants public const int ERROR_SUCCESS = 0; public const int ERROR_BUFFER_OVERFLOW = 111; #endregion Constants #region DN Parsing [DllImport("ntdsapi.dll", CharSet = CharSet.Unicode)] protected static extern int DsGetRdnW( ref IntPtr ppDN, ref int pcDN, out IntPtr ppKey, out int pcKey, out IntPtr ppVal, out int pcVal ); public static KeyValuePair<string, string> GetName(string distinguishedName) { IntPtr pDistinguishedName = Marshal.StringToHGlobalUni(distinguishedName); try { IntPtr pDN = pDistinguishedName, pKey, pVal; int cDN = distinguishedName.Length, cKey, cVal; int lastError = DsGetRdnW(ref pDN, ref cDN, out pKey, out cKey, out pVal, out cVal); if(lastError == ERROR_SUCCESS) { string key, value; if(cKey < 1) { key = string.Empty; } else { key = Marshal.PtrToStringUni(pKey, cKey); } if(cVal < 1) { value = string.Empty; } else { value = Marshal.PtrToStringUni(pVal, cVal); } return new KeyValuePair<string, string>(key, value); } else { throw new Win32Exception(lastError); } } finally { Marshal.FreeHGlobal(pDistinguishedName); } } public static IEnumerable<KeyValuePair<string, string>> ParseDN(string distinguishedName) { List<KeyValuePair<string, string>> components = new List<KeyValuePair<string, string>>(); IntPtr pDistinguishedName = Marshal.StringToHGlobalUni(distinguishedName); try { IntPtr pDN = pDistinguishedName, pKey, pVal; int cDN = distinguishedName.Length, cKey, cVal; do { int lastError = DsGetRdnW(ref pDN, ref cDN, out pKey, out cKey, out pVal, out cVal); if(lastError == ERROR_SUCCESS) { string key, value; if(cKey < 0) { key = null; } else if(cKey == 0) { key = string.Empty; } else { key = Marshal.PtrToStringUni(pKey, cKey); } if(cVal < 0) { value = null; } else if(cVal == 0) { value = string.Empty; } else { value = Marshal.PtrToStringUni(pVal, cVal); } components.Add(new KeyValuePair<string, string>(key, value)); pDN = (IntPtr)(pDN.ToInt64() + UnicodeEncoding.CharSize); //skip over comma cDN--; } else { throw new Win32Exception(lastError); } } while(cDN > 0); return components; } finally { Marshal.FreeHGlobal(pDistinguishedName); } } [DllImport("ntdsapi.dll", CharSet = CharSet.Unicode)] protected static extern int DsQuoteRdnValueW( int cUnquotedRdnValueLength, string psUnquotedRdnValue, ref int pcQuotedRdnValueLength, IntPtr psQuotedRdnValue ); public static string QuoteRDN(string rdn) { if (rdn == null) return null; int initialLength = rdn.Length; int quotedLength = 0; IntPtr pQuotedRDN = IntPtr.Zero; int lastError = DsQuoteRdnValueW(initialLength, rdn, ref quotedLength, pQuotedRDN); switch (lastError) { case ERROR_SUCCESS: { return string.Empty; } case ERROR_BUFFER_OVERFLOW: { break; //continue } default: { throw new Win32Exception(lastError); } } pQuotedRDN = Marshal.AllocHGlobal(quotedLength * UnicodeEncoding.CharSize); try { lastError = DsQuoteRdnValueW(initialLength, rdn, ref quotedLength, pQuotedRDN); switch(lastError) { case ERROR_SUCCESS: { return Marshal.PtrToStringUni(pQuotedRDN, quotedLength); } default: { throw new Win32Exception(lastError); } } } finally { if(pQuotedRDN != IntPtr.Zero) { Marshal.FreeHGlobal(pQuotedRDN); } } } [DllImport("ntdsapi.dll", CharSet = CharSet.Unicode)] protected static extern int DsUnquoteRdnValueW( int cQuotedRdnValueLength, string psQuotedRdnValue, ref int pcUnquotedRdnValueLength, IntPtr psUnquotedRdnValue ); public static string UnquoteRDN(string rdn) { if (rdn == null) return null; int initialLength = rdn.Length; int unquotedLength = 0; IntPtr pUnquotedRDN = IntPtr.Zero; int lastError = DsUnquoteRdnValueW(initialLength, rdn, ref unquotedLength, pUnquotedRDN); switch (lastError) { case ERROR_SUCCESS: { return string.Empty; } case ERROR_BUFFER_OVERFLOW: { break; //continue } default: { throw new Win32Exception(lastError); } } pUnquotedRDN = Marshal.AllocHGlobal(unquotedLength * UnicodeEncoding.CharSize); try { lastError = DsUnquoteRdnValueW(initialLength, rdn, ref unquotedLength, pUnquotedRDN); switch(lastError) { case ERROR_SUCCESS: { return Marshal.PtrToStringUni(pUnquotedRDN, unquotedLength); } default: { throw new Win32Exception(lastError); } } } finally { if(pUnquotedRDN != IntPtr.Zero) { Marshal.FreeHGlobal(pUnquotedRDN); } } } #endregion DN Parsing } public class DNComponent { public string Type { get; protected set; } public string EscapedValue { get; protected set; } public string UnescapedValue { get; protected set; } public string WholeComponent { get; protected set; } public DNComponent(string component, bool isEscaped) { string[] tokens = component.Split(new char[] { '=' }, 2); setup(tokens[0], tokens[1], isEscaped); } public DNComponent(string key, string value, bool isEscaped) { setup(key, value, isEscaped); } private void setup(string key, string value, bool isEscaped) { Type = key; if(isEscaped) { EscapedValue = value; UnescapedValue = Win32LDAP.UnquoteRDN(value); } else { EscapedValue = Win32LDAP.QuoteRDN(value); UnescapedValue = value; } WholeComponent = Type +"=" + EscapedValue; } public override bool Equals(object obj) { if (obj is DNComponent) { DNComponent dnObj = (DNComponent)obj; return dnObj.WholeComponent.Equals(this.WholeComponent, StringComparison.CurrentCultureIgnoreCase); } return base.Equals(obj); } public override int GetHashCode() { return WholeComponent.GetHashCode(); } } public class DistinguishedName { public DNComponent[] Components { get { return components.ToArray(); } } private List<DNComponent> components; private string cachedDN; public DistinguishedName(string distinguishedName) { cachedDN = distinguishedName; components = new List<DNComponent>(); foreach (KeyValuePair<string, string> kvp in Win32LDAP.ParseDN(distinguishedName)) { components.Add(new DNComponent(kvp.Key, kvp.Value, true)); } } public DistinguishedName(IEnumerable<DNComponent> dnComponents) { components = new List<DNComponent>(dnComponents); cachedDN = GetWholePath(","); } public bool Contains(DNComponent dnComponent) { return components.Contains(dnComponent); } public string GetDNSDomainName() { List<string> dcs = new List<string>(); foreach (DNComponent dnc in components) { if(dnc.Type.Equals("DC", StringComparison.CurrentCultureIgnoreCase)) { dcs.Add(dnc.UnescapedValue); } } return string.Join(".", dcs.ToArray()); } public string GetDomainDN() { List<string> dcs = new List<string>(); foreach (DNComponent dnc in components) { if(dnc.Type.Equals("DC", StringComparison.CurrentCultureIgnoreCase)) { dcs.Add(dnc.WholeComponent); } } return string.Join(",", dcs.ToArray()); } public string GetWholePath() { return GetWholePath(","); } public string GetWholePath(string separator) { List<string> parts = new List<string>(); foreach (DNComponent component in components) { parts.Add(component.WholeComponent); } return string.Join(separator, parts.ToArray()); } public DistinguishedName GetParent() { if(components.Count == 1) { return null; } List<DNComponent> tempList = new List<DNComponent>(components); tempList.RemoveAt(0); return new DistinguishedName(tempList); } public override bool Equals(object obj) { if(obj is DistinguishedName) { DistinguishedName objDN = (DistinguishedName)obj; if (this.Components.Length == objDN.Components.Length) { for (int i = 0; i < this.Components.Length; i++) { if (!this.Components[i].Equals(objDN.Components[i])) { return false; } } return true; } return false; } return base.Equals(obj); } public override int GetHashCode() { return cachedDN.GetHashCode(); } } |
这个扩展的正则表达式不需要较少的资源。
1 2 3 4 5 6 7 8 9 10 | public static int CountSubstring(this string text, string value) { int count = 0, minIndex = text.IndexOf(value, 0); while (minIndex != -1) { minIndex = text.IndexOf(value, minIndex + value.Length); count++; } return count; } |
用法:
1 2 | MyString ="OU=Level3,OU=Level2,OU=Level1,DC=domain,DC=com"; int count = MyString.CountSubstring("OU="); |
如果以下工作
1 2 | MyString ="OU=Level3,OU=Level2,OU=Level1,DC=domain,DC=com"; int count = Regex.Matches(MyString,"OU=").Count |
1 2 3 | int count = myString.Split(new []{','}) .Count(item => item.StartsWith( "OU=", StringComparison.OrdinalIgnoreCase)) |
在这两个例子是如何你可以得到的结果,你正在寻找
1 | var MyString ="OU=Level3,OU=Level2,OU=Level1,DC=domain,DC=com"; |
这一点你会看到列表中的值,但它也有一个分隔的想法只是一对直流分割字符串,并显示与工作。
1 |
这一个将返回你的只有3分和对这样的项目的列表,如果你不依赖于计数,这是可以验证的visually收益= 3的水平`或`
1 2 3 | var lstSplit = MyString.Split(new[] { ',' }) .Where(splitItem => splitItem.StartsWith( "OU=", StringComparison.OrdinalIgnoreCase)).ToList(); |
1 2 3 4 | public static int CountOccurences(string needle, string haystack) { return (haystack.Length - haystack.Replace(needle,"").Length) / needle.Length; } |
它的答案,对其他benchmarked(正则表达式在一个一个的"指数"),作品。。。。。。。。