我正在做某件事,我意识到我想计算一个字符串中可以找到多少个/秒,然后让我感到震惊的是,有几种方法可以做到,但无法决定最好的(或最简单的)是。

目前,我正在处理类似:

string source = "/once/upon/a/time/";
int count = source.Length - source.Replace("/", "").Length;

但是,我一点都不喜欢它,对吗?

我真的不想为此挖掘RegEx ,对吗?

我知道我的字符串将包含我要搜索的术语,因此可以假定...

当然,对于其中的字符串长度> 1,

string haystack = "/once/upon/a/time";
string needle = "/";
int needleCount = ( haystack.Length - haystack.Replace(needle,"").Length ) / needle.Length;

#1楼

string Name = "Very good nice one is very good but is very good nice one this is called the term";
bool valid=true;
int count = 0;
int k=0;
int m = 0;
while (valid)
{k = Name.Substring(m,Name.Length-m).IndexOf("good");if (k != -1){count++;m = m + k + 4;}elsevalid = false;
}
Console.WriteLine(count + " Times accures");

#2楼

我进行了一些研究,发现Richard Watson的解决方案在大多数情况下是最快的。 这就是该表中包含每个解决方案的结果的表(那些使用Regex的解决方案除外,因为使用Regex的原因是在解析“ test {test”之类的字符串时会抛出异常)

    Name      | Short/char |  Long/char | Short/short| Long/short |  Long/long |Inspite   |         134|        1853|          95|        1146|         671|LukeH_1   |         346|        4490|         N/A|         N/A|         N/A|LukeH_2   |         152|        1569|         197|        2425|        2171|
Bobwienholt   |         230|        3269|         N/A|         N/A|         N/A|
Richard Watson|          33|         298|         146|         737|         543|
StefanosKargas|         N/A|         N/A|         681|       11884|       12486|

您会看到,如果在短字符串(10至50个字符)中发现短子字符串(1-5个字符)的出现次数,则首选原始算法。

另外,对于多字符子字符串,应使用以下代码(基于Richard Watson的解决方案)

int count = 0, n = 0;if(substring != "")
{while ((n = source.IndexOf(substring, n, StringComparison.InvariantCulture)) != -1){n += substring.Length;++count;}
}

#3楼

string source = "/once/upon/a/time/";
int count = 0, n = 0;
while ((n = source.IndexOf('/', n) + 1) != 0) count++;

Richard Watson答案的一种变体,字符串中出现char的次数越多,速度越快,效率越高,代码更少!

尽管我必须说,在没有广泛测试每种情况的情况下,我确实看到通过使用以下方法可以显着提高速度:

int count = 0;
for (int n = 0; n < source.Length; n++) if (source[n] == '/') count++;

#4楼

public static int GetNumSubstringOccurrences(string text, string search)
{int num = 0;int pos = 0;if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(search)){while ((pos = text.IndexOf(search, pos)) > -1){num ++;pos += search.Length;}}return num;
}

#5楼

            var conditionalStatement = conditionSetting.Value;//order of replace matters, remove == before =, incase of ===conditionalStatement = conditionalStatement.Replace("==", "~").Replace("!=", "~").Replace('=', '~').Replace('!', '~').Replace('>', '~').Replace('<', '~').Replace(">=", "~").Replace("<=", "~");var listOfValidConditions = new List<string>() { "!=", "==", ">", "<", ">=", "<=" };if (conditionalStatement.Count(x => x == '~') != 1){result.InvalidFieldList.Add(new KeyFieldData(batch.DECurrentField, "The IsDoubleKeyCondition does not contain a supported conditional statement. Contact System Administrator."));result.Status = ValidatorStatus.Fail;return result;}

需要执行类似于测试字符串中的条件语句的操作。

用单个字符替换了我正在寻找的内容,并计算了单个字符的实例。

显然,在进行此操作之前,需要检查您正在使用的单个字符在字符串中是否不存在,以避免计数错误。


#6楼

我认为最简单的方法是使用正则表达式。 这样,您可以获得与使用myVar.Split('x')相同的拆分计数,但使用的是多字符设置。

string myVar = "do this to count the number of words in my wording so that I can word it up!";
int count = Regex.Split(myVar, "word").Length;

#7楼

Regex.Matches(input,  Regex.Escape("stringToMatch")).Count

#8楼

对于任何想使用String扩展方法的人,

这是我使用的,这是基于最好的发布答案的:

public static class StringExtension
{    /// <summary> Returns the number of occurences of a string within a string, optional comparison allows case and culture control. </summary>public static int Occurrences(this System.String input, string value, StringComparison stringComparisonType = StringComparison.Ordinal){if (String.IsNullOrEmpty(value)) return 0;int count    = 0;int position = 0;while ((position = input.IndexOf(value, position, stringComparisonType)) != -1){position += value.Length;count    += 1;}return count;}/// <summary> Returns the number of occurences of a single character within a string. </summary>public static int Occurrences(this System.String input, char value){int count = 0;foreach (char c in input) if (c == value) count += 1;return count;}
}

#9楼

string s = "HOWLYH THIS ACTUALLY WORKSH WOWH";
int count = 0;
for (int i = 0; i < s.Length; i++)if (s[i] == 'H') count++;

它仅检查字符串中的每个字符,如果该字符是您要搜索的字符,请添加一个以进行计数。


#10楼

如果您查看此网页 ,则会对15种不同的方法进行基准测试,包括使用并行循环。

最快的方法似乎是使用单线程for循环(如果您的.Net版本<4.0)或parallel.for循环(如果使用.Net> 4.0并进行了数千次检查)。

假设“ ss”是您的搜索字符串,“ ch”是您的字符数组(如果要查找的字符超过一个),这是单线程运行时间最快的代码的基本要点:

for (int x = 0; x < ss.Length; x++)
{for (int y = 0; y < ch.Length; y++){for (int a = 0; a < ss[x].Length; a++ ){if (ss[x][a] == ch[y])//it's found. DO what you need to here.}}
}

还提供了基准测试源代码,因此您可以运行自己的测试。


#11楼

字符串中的字符串:

在“ .. JD JD JD JD等,等等。JDJDJDJDJDJDJDJD等”中找到“ etc”。

var strOrigin = " .. JD JD JD JD etc. and etc. JDJDJDJDJDJDJDJD and etc.";
var searchStr = "etc";
int count = (strOrigin.Length - strOrigin.Replace(searchStr, "").Length)/searchStr.Length.

在将其作为不健全/笨拙的东西丢弃之前,请检查性能。


#12楼

以为我会把我的扩展方法丢进去(更多信息请参见评论)。 我没有做任何正式的基准测试,但是我认为在大多数情况下必须非常快。

编辑:好的-所以这个问题让我想知道我们当前实现的性能如何与此处介绍的一些解决方案相提并论。 我决定进行一些基准测试,发现我们的解决方案与Richard Watson提供的解决方案的性能非常一致,直到您使用大字符串(100 Kb +),大子字符串(32 Kb + )和许多嵌入式重复(10K +)。 到那时,我们的解决方案要慢2到4倍。 考虑到这一点以及我们真的很喜欢Richard Watson提出的解决方案这一事实,我们相应地重构了我们的解决方案。 我只是想将其提供给可能会从中受益的任何人。

我们原始的解决方案:

    /// <summary>/// Counts the number of occurrences of the specified substring within/// the current string./// </summary>/// <param name="s">The current string.</param>/// <param name="substring">The substring we are searching for.</param>/// <param name="aggressiveSearch">Indicates whether or not the algorithm /// should be aggressive in its search behavior (see Remarks). Default /// behavior is non-aggressive.</param>/// <remarks>This algorithm has two search modes - aggressive and /// non-aggressive. When in aggressive search mode (aggressiveSearch = /// true), the algorithm will try to match at every possible starting /// character index within the string. When false, all subsequent /// character indexes within a substring match will not be evaluated. /// For example, if the string was 'abbbc' and we were searching for /// the substring 'bb', then aggressive search would find 2 matches /// with starting indexes of 1 and 2. Non aggressive search would find /// just 1 match with starting index at 1. After the match was made, /// the non aggressive search would attempt to make it's next match /// starting at index 3 instead of 2.</remarks>/// <returns>The count of occurrences of the substring within the string.</returns>public static int CountOccurrences(this string s, string substring, bool aggressiveSearch = false){// if s or substring is null or empty, substring cannot be found in sif (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(substring))return 0;// if the length of substring is greater than the length of s,// substring cannot be found in sif (substring.Length > s.Length)return 0;var sChars = s.ToCharArray();var substringChars = substring.ToCharArray();var count = 0;var sCharsIndex = 0;// substring cannot start in s beyond following indexvar lastStartIndex = sChars.Length - substringChars.Length;while (sCharsIndex <= lastStartIndex){if (sChars[sCharsIndex] == substringChars[0]){// potential match checkingvar match = true;var offset = 1;while (offset < substringChars.Length){if (sChars[sCharsIndex + offset] != substringChars[offset]){match = false;break;}offset++;}if (match){count++;// if aggressive, just advance to next char in s, otherwise, // skip past the match just found in ssCharsIndex += aggressiveSearch ? 1 : substringChars.Length;}else{// no match found, just move to next char in ssCharsIndex++;}}else{// no match at current index, move alongsCharsIndex++;}}return count;}

这是我们修改后的解决方案:

    /// <summary>/// Counts the number of occurrences of the specified substring within/// the current string./// </summary>/// <param name="s">The current string.</param>/// <param name="substring">The substring we are searching for.</param>/// <param name="aggressiveSearch">Indicates whether or not the algorithm /// should be aggressive in its search behavior (see Remarks). Default /// behavior is non-aggressive.</param>/// <remarks>This algorithm has two search modes - aggressive and /// non-aggressive. When in aggressive search mode (aggressiveSearch = /// true), the algorithm will try to match at every possible starting /// character index within the string. When false, all subsequent /// character indexes within a substring match will not be evaluated. /// For example, if the string was 'abbbc' and we were searching for /// the substring 'bb', then aggressive search would find 2 matches /// with starting indexes of 1 and 2. Non aggressive search would find /// just 1 match with starting index at 1. After the match was made, /// the non aggressive search would attempt to make it's next match /// starting at index 3 instead of 2.</remarks>/// <returns>The count of occurrences of the substring within the string.</returns>public static int CountOccurrences(this string s, string substring, bool aggressiveSearch = false){// if s or substring is null or empty, substring cannot be found in sif (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(substring))return 0;// if the length of substring is greater than the length of s,// substring cannot be found in sif (substring.Length > s.Length)return 0;int count = 0, n = 0;while ((n = s.IndexOf(substring, n, StringComparison.InvariantCulture)) != -1){if (aggressiveSearch)n++;elsen += substring.Length;count++;}return count;}

#13楼

string search = "/string";
var occurrences = (regex.Match(search, @"\/")).Count;

每次程序精确地找到“ / s”(区分大小写)时,它将进行计数,并且其出现的次数将存储在变量“ occurrences”中


#14楼

我最初给我的东西是:

public static int CountOccurrences(string original, string substring)
{if (string.IsNullOrEmpty(substring))return 0;if (substring.Length == 1)return CountOccurrences(original, substring[0]);if (string.IsNullOrEmpty(original) ||substring.Length > original.Length)return 0;int substringCount = 0;for (int charIndex = 0; charIndex < original.Length; charIndex++){for (int subCharIndex = 0, secondaryCharIndex = charIndex; subCharIndex < substring.Length && secondaryCharIndex < original.Length; subCharIndex++, secondaryCharIndex++){if (substring[subCharIndex] != original[secondaryCharIndex])goto continueOuter;}if (charIndex + substring.Length > original.Length)break;charIndex += substring.Length - 1;substringCount++;continueOuter:;}return substringCount;
}public static int CountOccurrences(string original, char @char)
{if (string.IsNullOrEmpty(original))return 0;int substringCount = 0;for (int charIndex = 0; charIndex < original.Length; charIndex++)if (@char == original[charIndex])substringCount++;return substringCount;
}

使用替换和分割的干草堆方法中的针产生21+秒,而这大约需要15.2。

在添加了将要添加substring.Length - 1的字符之后进行编辑(就像应该的那样),它的时间为11.6秒。

编辑2:我使用了一个包含26个两个字符的字符串,这是将时间更新为相同的示例文本:

大海捞针(OP版):7.8秒

建议的机制:4.6秒。

编辑3:添加单个字符的大写字母,到1.2秒。

编辑4:对于上下文:使用了5000万次迭代。


#15楼

在C#中,一个不错的String SubString计数器是这个异常棘手的家伙:

public static int CCount(String haystack, String needle)
{return haystack.Split(new[] { needle }, StringSplitOptions.None).Length - 1;
}

#16楼

int count = new Regex(Regex.Escape(needle)).Matches(haystack).Count;

#17楼

string s = "65 fght 6565 4665 hjk";
int count = 0;
foreach (Match m in Regex.Matches(s, "65"))count++;

#18楼

对于字符串定界符(如主题所述,不用于char大小写):
字符串来源=“ @@@ once @@@ upon @@@ aa @@@ time @@@”;
int count = source.Split(new [] {“ @@@”},StringSplitOptions.RemoveEmptyEntries).Length-1;

张贴者的原始源值(“ / once / upon / a / time /”)自然定界符是char'/',并且响应的确说明了source.Split(char [])选项。


#19楼

private int CountWords(string text, string word) {int count = (text.Length - text.Replace(word, "").Length) / word.Length;return count;
}

因为最初的解决方案对于chars来说是最快的,所以我想它对于字符串也是一样。 这是我的贡献。

对于上下文:我正在日志文件中查找“失败”和“成功”之类的词。

Gr,本


#20楼

我觉得我们缺少某些类型的子字符串计数,例如不安全的逐字节比较。 我汇总了原始海报的方法以及我能想到的任何方法。

这些是我做的字符串扩展。

namespace Example
{using System;using System.Text;public static class StringExtensions{public static int CountSubstr(this string str, string substr){return (str.Length - str.Replace(substr, "").Length) / substr.Length;}public static int CountSubstr(this string str, char substr){return (str.Length - str.Replace(substr.ToString(), "").Length);}public static int CountSubstr2(this string str, string substr){int substrlen = substr.Length;int lastIndex = str.IndexOf(substr, 0, StringComparison.Ordinal);int count = 0;while (lastIndex != -1){++count;lastIndex = str.IndexOf(substr, lastIndex + substrlen, StringComparison.Ordinal);}return count;}public static int CountSubstr2(this string str, char substr){int lastIndex = str.IndexOf(substr, 0);int count = 0;while (lastIndex != -1){++count;lastIndex = str.IndexOf(substr, lastIndex + 1);}return count;}public static int CountChar(this string str, char substr){int length = str.Length;int count = 0;for (int i = 0; i < length; ++i)if (str[i] == substr)++count;return count;}public static int CountChar2(this string str, char substr){int count = 0;foreach (var c in str)if (c == substr)++count;return count;}public static unsafe int CountChar3(this string str, char substr){int length = str.Length;int count = 0;fixed (char* chars = str){for (int i = 0; i < length; ++i)if (*(chars + i) == substr)++count;}return count;}public static unsafe int CountChar4(this string str, char substr){int length = str.Length;int count = 0;fixed (char* chars = str){for (int i = length - 1; i >= 0; --i)if (*(chars + i) == substr)++count;}return count;}public static unsafe int CountSubstr3(this string str, string substr){int length = str.Length;int substrlen = substr.Length;int count = 0;fixed (char* strc = str){fixed (char* substrc = substr){int n = 0;for (int i = 0; i < length; ++i){if (*(strc + i) == *(substrc + n)){++n;if (n == substrlen){++count;n = 0;}}elsen = 0;}}}return count;}public static int CountSubstr3(this string str, char substr){return CountSubstr3(str, substr.ToString());}public static unsafe int CountSubstr4(this string str, string substr){int length = str.Length;int substrLastIndex = substr.Length - 1;int count = 0;fixed (char* strc = str){fixed (char* substrc = substr){int n = substrLastIndex;for (int i = length - 1; i >= 0; --i){if (*(strc + i) == *(substrc + n)){if (--n == -1){++count;n = substrLastIndex;}}elsen = substrLastIndex;}}}return count;}public static int CountSubstr4(this string str, char substr){return CountSubstr4(str, substr.ToString());}}
}

接下来是测试代码...

static void Main()
{const char matchA = '_';const string matchB = "and";const string matchC = "muchlongerword";const string testStrA = "_and_d_e_banna_i_o___pfasd__and_d_e_banna_i_o___pfasd_";const string testStrB = "and sdf and ans andeians andano ip and and sdf and ans andeians andano ip and";const string testStrC ="muchlongerword amuchlongerworsdfmuchlongerwordsdf jmuchlongerworijv muchlongerword sdmuchlongerword dsmuchlongerword";const int testSize = 1000000;Console.WriteLine(testStrA.CountSubstr('_'));Console.WriteLine(testStrA.CountSubstr2('_'));Console.WriteLine(testStrA.CountSubstr3('_'));Console.WriteLine(testStrA.CountSubstr4('_'));Console.WriteLine(testStrA.CountChar('_'));Console.WriteLine(testStrA.CountChar2('_'));Console.WriteLine(testStrA.CountChar3('_'));Console.WriteLine(testStrA.CountChar4('_'));Console.WriteLine(testStrB.CountSubstr("and"));Console.WriteLine(testStrB.CountSubstr2("and"));Console.WriteLine(testStrB.CountSubstr3("and"));Console.WriteLine(testStrB.CountSubstr4("and"));Console.WriteLine(testStrC.CountSubstr("muchlongerword"));Console.WriteLine(testStrC.CountSubstr2("muchlongerword"));Console.WriteLine(testStrC.CountSubstr3("muchlongerword"));Console.WriteLine(testStrC.CountSubstr4("muchlongerword"));var timer = new Stopwatch();timer.Start();for (int i = 0; i < testSize; ++i)testStrA.CountSubstr(matchA);timer.Stop();Console.WriteLine("CS1 chr: " + timer.Elapsed.TotalMilliseconds + "ms");timer.Restart();for (int i = 0; i < testSize; ++i)testStrB.CountSubstr(matchB);timer.Stop();Console.WriteLine("CS1 and: " + timer.Elapsed.TotalMilliseconds + "ms");timer.Restart();for (int i = 0; i < testSize; ++i)testStrC.CountSubstr(matchC);timer.Stop();Console.WriteLine("CS1 mlw: " + timer.Elapsed.TotalMilliseconds + "ms");timer.Restart();for (int i = 0; i < testSize; ++i)testStrA.CountSubstr2(matchA);timer.Stop();Console.WriteLine("CS2 chr: " + timer.Elapsed.TotalMilliseconds + "ms");timer.Restart();for (int i = 0; i < testSize; ++i)testStrB.CountSubstr2(matchB);timer.Stop();Console.WriteLine("CS2 and: " + timer.Elapsed.TotalMilliseconds + "ms");timer.Restart();for (int i = 0; i < testSize; ++i)testStrC.CountSubstr2(matchC);timer.Stop();Console.WriteLine("CS2 mlw: " + timer.Elapsed.TotalMilliseconds + "ms");timer.Restart();for (int i = 0; i < testSize; ++i)testStrA.CountSubstr3(matchA);timer.Stop();Console.WriteLine("CS3 chr: " + timer.Elapsed.TotalMilliseconds + "ms");timer.Restart();for (int i = 0; i < testSize; ++i)testStrB.CountSubstr3(matchB);timer.Stop();Console.WriteLine("CS3 and: " + timer.Elapsed.TotalMilliseconds + "ms");timer.Restart();for (int i = 0; i < testSize; ++i)testStrC.CountSubstr3(matchC);timer.Stop();Console.WriteLine("CS3 mlw: " + timer.Elapsed.TotalMilliseconds + "ms");timer.Restart();for (int i = 0; i < testSize; ++i)testStrA.CountSubstr4(matchA);timer.Stop();Console.WriteLine("CS4 chr: " + timer.Elapsed.TotalMilliseconds + "ms");timer.Restart();for (int i = 0; i < testSize; ++i)testStrB.CountSubstr4(matchB);timer.Stop();Console.WriteLine("CS4 and: " + timer.Elapsed.TotalMilliseconds + "ms");timer.Restart();for (int i = 0; i < testSize; ++i)testStrC.CountSubstr4(matchC);timer.Stop();Console.WriteLine("CS4 mlw: " + timer.Elapsed.TotalMilliseconds + "ms");timer.Restart();for (int i = 0; i < testSize; ++i)testStrA.CountChar(matchA);timer.Stop();Console.WriteLine("CC1 chr: " + timer.Elapsed.TotalMilliseconds + "ms");timer.Restart();for (int i = 0; i < testSize; ++i)testStrA.CountChar2(matchA);timer.Stop();Console.WriteLine("CC2 chr: " + timer.Elapsed.TotalMilliseconds + "ms");timer.Restart();for (int i = 0; i < testSize; ++i)testStrA.CountChar3(matchA);timer.Stop();Console.WriteLine("CC3 chr: " + timer.Elapsed.TotalMilliseconds + "ms");timer.Restart();for (int i = 0; i < testSize; ++i)testStrA.CountChar4(matchA);timer.Stop();Console.WriteLine("CC4 chr: " + timer.Elapsed.TotalMilliseconds + "ms");
}

结果:CSX对应于CountSubstrX,CCX对应于CountCharX。 “ chr”在字符串中搜索“ _”,“ and”在字符串中搜索“ and”,而“ mlw”在字符串中搜索“ muchlongerword”

CS1 chr: 824.123ms
CS1 and: 586.1893ms
CS1 mlw: 486.5414ms
CS2 chr: 127.8941ms
CS2 and: 806.3918ms
CS2 mlw: 497.318ms
CS3 chr: 201.8896ms
CS3 and: 124.0675ms
CS3 mlw: 212.8341ms
CS4 chr: 81.5183ms
CS4 and: 92.0615ms
CS4 mlw: 116.2197ms
CC1 chr: 66.4078ms
CC2 chr: 64.0161ms
CC3 chr: 65.9013ms
CC4 chr: 65.8206ms

最后,我有一个包含360万个字符的文件。 重复了100,000次“ derp adfderdserp dfaerpderp deasderp”。 我使用上述方法在文件内搜索“ derp”,结果是这些结果的100倍。

CS1Derp: 1501.3444ms
CS2Derp: 1585.797ms
CS3Derp: 376.0937ms
CS4Derp: 271.1663ms

因此,我的第四种方法绝对是赢家,但实际上,如果一个360万个字符文件100次仅花了1586毫秒(最糟糕的情况),那么所有这些都可以忽略不计。

顺便说一句,我还使用100倍CountSubstr和CountChar方法扫描了360万个字符文件中的'd'char。 结果...

CS1  d : 2606.9513ms
CS2  d : 339.7942ms
CS3  d : 960.281ms
CS4  d : 233.3442ms
CC1  d : 302.4122ms
CC2  d : 280.7719ms
CC3  d : 299.1125ms
CC4  d : 292.9365ms

据此,原始的海报方法对于大干草堆中的单个字符的针非常不利。

注意:所有值已更新为“发行版本”输出。 我第一次发布此内容时,意外地忘记了建立在Release模式上。 我的某些声明已被修改。


#21楼

string source = "/once/upon/a/time/";
int count = 0;
foreach (char c in source) if (c == '/') count++;

本身必须比source.Replace()更快。


#22楼

LINQ适用于所有集合,并且由于字符串只是字符的集合,所以这个漂亮的小单行代码怎么样:

var count = source.Count(c => c == '/');

确保已using System.Linq; 在代码文件的顶部,因为.Count是该命名空间的扩展方法。


#23楼

如果您使用的是.NET 3.5,则可以使用LINQ以单线方式执行此操作:

int count = source.Count(f => f == '/');

如果您不想使用LINQ,可以使用以下方法:

int count = source.Split('/').Length - 1;

您可能会惊讶地发现您的原始技术似乎比这两种技术都快30%! 我刚刚使用“ / once / upon / a / time /”做了一个快速基准测试,结果如下:

你原来的= 12秒
source.Count = 19秒
source.Split = 17秒
foreach( 根据bobwienholt的回答 )= 10s

(时间是进行5000万次迭代,因此您不太可能注意到现实世界中的巨大差异。)


#24楼

这两个都只适用于单字符搜索词...

countOccurences("the", "the answer is the answer");int countOccurences(string needle, string haystack)
{return (haystack.Length - haystack.Replace(needle,"").Length) / needle.Length;
}

对于更长的针头可能会更好...

但是必须有一种更优雅的方法。 :)


#25楼

如果您希望能够搜索整个字符串,而不仅仅是字符:

src.Select((c, i) => src.Substring(i)).Count(sub => sub.StartsWith(target))

读为“对于字符串中的每个字符,将从该字符开始的其余字符串作为子字符串;如果它以目标字符串开头,则对其进行计数”。


#26楼

编辑:

source.Split('/').Length-1

#27楼

使用System.Linq;

int CountOf =>“ A :: BC :: D” .Split(“ ::”)。长度-1;


#28楼

string source = "/once/upon/a/time/";
int count = 0;
int n = 0;while ((n = source.IndexOf('/', n)) != -1)
{n++;count++;
}

在我的计算机上,它比每个字符的解决方案都要快2秒钟,可以进行5000万次迭代。

2013年修订版:

将字符串更改为char []并进行迭代。 将总时间再减少一到两秒,即可进行50m次迭代!

char[] testchars = source.ToCharArray();
foreach (char c in testchars)
{if (c == '/')count++;
}

这仍然更快:

char[] testchars = source.ToCharArray();
int length = testchars.Length;
for (int n = 0; n < length; n++)
{if (testchars[n] == '/')count++;
}

从好的角度来看,从数​​组末尾迭代到0似乎是最快的,大约是5%。

int length = testchars.Length;
for (int n = length-1; n >= 0; n--)
{if (testchars[n] == '/')count++;
}

我想知道为什么会这样并且正在谷歌搜索(我记得更快地进行了反向迭代),并遇到了这个SO问题,它已经烦人地使用了字符串char []技术。 我认为,在这种情况下,逆转技巧是新的。

在C#中,迭代字符串中各个字符的最快方法是什么?


#29楼

str="aaabbbbjjja";
int count = 0;
int size = str.Length;string[] strarray = new string[size];
for (int i = 0; i < str.Length; i++)
{strarray[i] = str.Substring(i, 1);
}
Array.Sort(strarray);
str = "";
for (int i = 0; i < strarray.Length - 1; i++)
{if (strarray[i] == strarray[i + 1]){count++;}else{count++;str = str + strarray[i] + count;count = 0;}}
count++;
str = str + strarray[strarray.Length - 1] + count;

这是为了计算字符的出现。 对于此示例,输出将为“ a4b4j3”


#30楼

出现字符串的通用函数:

public int getNumberOfOccurencies(String inputString, String checkString)
{if (checkString.Length > inputString.Length || checkString.Equals("")) { return 0; }int lengthDifference = inputString.Length - checkString.Length;int occurencies = 0;for (int i = 0; i < lengthDifference; i++) {if (inputString.Substring(i, checkString.Length).Equals(checkString)) { occurencies++; i += checkString.Length - 1; } }return occurencies;
}

您如何计算字符串中字符串(实际上是字符)的出现?相关推荐

  1. 如何从字符串中删除最后一个字符?

    我想从字符串中删除最后一个字符. 我尝试这样做: public String method(String str) {if (str.charAt(str.length()-1)=='x'){str ...

  2. 程序员面试题精选100题(36)-在字符串中删除特定的字符[算法]

    题目:输入两个字符串,从第一字符串中删除第二个字符串中所有的字符.例如,输入"They are students."和"aeiou",则删除之后的第一个字符串变 ...

  3. java随机数去重排序_数组去重及排序/0~10随机数字/字符串中出现最多的字符及次数...

    数组去重及排序: var arr = [1,5,1,2,6,8,1,81,9,0]; for(var i=0;i for(var j=i+1;j if(arr[i] == arr[j]){ arr.s ...

  4. php 是否包含 大写,PHP检查字符串中是否包含大写字符

    PHP检查字符串中是否包含大写字符,也就是判断指定字符串中是否全为小写.我们可以通过for循环以及strlen().ord()函数来实现. 下面我们就结合具体的代码示例,给大家介绍PHP检查字符串中是 ...

  5. C语言字符串中删除重复的字符的算法(附完整源码)

    C语言字符串中删除重复的字符的算法 C语言字符串中删除重复的字符的算法完整源码(定义,实现,main函数测试) C语言字符串中删除重复的字符的算法完整源码(定义,实现,main函数测试) #inclu ...

  6. php取掉字符串第一位支付,php怎样去掉字符串中的第一个字符

    php去掉字符串中的第一个字符的方法:可以利用substr()函数来实现.substr()函数可以返回字符串的提取部分,如果失败则返回false,或者返回一个空字符串. substr() 函数返回字符 ...

  7. 《Python CookBook2》 第一章 文本 - 检查字符串中是否包含某字符集合中的字符 简化字符串的translate方法的使用...

    检查字符串中是否包含某字符集合中的字符  任务: 检查字符串中是否出现了某个字符集合中的字符 解决方案: 方案一: import itertoolsdef containAny(seq,aset):f ...

  8. 字符串 charat_Java | String.charAt(index)| 从字符串中按索引获取字符

    字符串 charat String.charAt() function is a library function of String class, it is used to get/retriev ...

  9. php 字符串 替换 最后,php如何替换字符串中的最后一个字符

    php替换字符串中的最后一个字符的方法是:可以通过preg_replace()函数来实现.该函数的语法为:[preg_replace(mixed $pattern, mixed $replacemen ...

  10. 《Python Cookbook 3rd》笔记(2.11):删除字符串中不需要的字符

    删除字符串中不需要的字符 问题 你想去掉文本字符串开头,结尾或者中间不想要的字符,比如空白 解法 strip() 方法能用于删除开始或结尾的字符. lstrip() 和 rstrip() 分别从左和从 ...

最新文章

  1. software RAID0+cryptsetup磁盘加密
  2. 波士顿动力机器狗新技能!跳绳园艺做家务,还有书法神技
  3. antd中的form表单 initialValue导致数据不更新问题
  4. linux反调试代码,linux反调试方法
  5. 函 float *search(float(*pointer)[4],int n)
  6. 谈谈你对MVC和三层架构的理解?(月薪三万的面试题)
  7. 经典FOXMAIL报错 winsock error 11004
  8. ubuntu卸载openjdk-11
  9. 10个步骤的筛选器模式
  10. 创建单IP的***网络
  11. 基于JAVA+SpringBoot+Mybatis+MYSQL的体育馆开放管理系统
  12. mysql命令语句来去除掉字段中空格字符的方法
  13. 两天来的Java IO Tips
  14. linux下设置set位权限,网络安全系列之四十 在Linux中设置SET位权限
  15. CSS控制文本超出指定宽度显示省略号和文本不换行
  16. java100集视频_上百集课程JAVA区块链开发视频教程
  17. pygame游戏教程目录
  18. 【SLAM学习笔记】10-ORB_SLAM3关键源码分析⑧ Optimizer(五)sim3优化
  19. 自己动手设计一个简单的HTML网页
  20. 电脑连上网却无法使用浏览器,显示远程计算机或设备将不接受连接的解决办法

热门文章

  1. Android JetPack Lifecycle源码解析
  2. Settings.System暂存/读取数据
  3. 第十三周项目二-动物这样叫(1)
  4. Linux用init命令关机、重启、切换模式
  5. python 做山水画_服了!年度最强的编程语言来了!它不是Python!
  6. (iOS-框架封装)AFN3.x 网络请求封装
  7. Linux 永久挂载(mount)
  8. 流式套接字:基于TCP协议的Socket网络编程(案例2)
  9. 如何阻止子元素触发父元素的事件
  10. python学习之if条件句的使用