The first way to think of this is, of course, to iterate through the string and count:
Copy Code code as follows:
c1=0;
for (Inti=0;i {
if (str[i]== ' A ')
{
c1++;
}
}
The second method is also easy to think of, remove all the characters in the string to find, and then compare the length of the string before and after the removal. This method has been despised by someone who is said to be poor in performance and takes up more space.
Copy Code code as follows:
C2=str. Length-str.replace ("A", String.Empty). Length;
Then someone comes up with a third method, separating the original string into substrings with the characters you want to find, and then finding the number of substrings. This is a short way to write in C #:
Copy Code code as follows:
C3=str. Split (newchar[]{' A '}). Length-1;
We can deduce the order of the three performance from the principle, but the difference is how much, or to test. This is a very classic test code:
Copy Code code as follows:
Stringstr= "Sadthdgsafsdgtghrdgsadfaddrhdfsgasdaa";
Stopwatchsw=newstopwatch ();
Longt;
intc=0;
Gc. Collect ();
Application.doevents ();
Sw. Start ();
for (inti=0;i<100000;i++)
{
Three algorithms of c=
}
Sw. Stop ();
T=SW. Elapsedmilliseconds;
First of all, we ensure correctness, tested three methods can correctly handle a variety of situations, including end to end, continuous occurrence, does not appear or string length of 0, I took the string is a very common string. Compile to release version, run 10 times and get the following results:
Traversal statistics: 13 ms
Compare length after replacement: 112 ms
Count after breaking string: 233 ms
There is already a difference, the traversal statistics are 10 times times faster than the replacement, and the break string is slower. Next I did the following two tests:
1. Do not change the length of the string, increase or decrease the number of strings to find.
2, do not change the frequency to find characters appear, but increase the length of the string.
The results show that three methods increase linearly with the length of the string, and the latter two methods slow down as the character to look for increases.
The method of breaking a string is also affected by the distribution of the string you want to find.
The implementation of the Replace function and the Split function can solve this problem completely. However, I am not in the mood to study carefully, I decided to choose the second method-the replacement after the length of comparison. Although its speed is slower than the first method, it is easy to rewrite to find a way to count the number of substrings with a length of not 1. The first method if the length is greater than 1 of the string to consider a number of factors (although not necessarily really troublesome), I am too lazy to think, hehe.