04. august 2005 - 01:10Der er
16 kommentarer og 2 løsninger
Tælle tegn i C#
Hej...
Vil tælle hvor mange fx A´er der er i en streng... hhm... er der en lettere og bedre metode end at kører alle tegnene igennem, og så tælle op når et A bliver mødt?
Hmm, bare træls, det er jo fordi at der er while (true), eller while (!done) på... og hvis jeg så sætter done til true, så skal jeg reconnecte, for at den logger ud. Har så lyst halvdelen af det, ved at "smadre" listener, ved en close og en fejl meddelse...
using System; using System.Text.RegularExpressions;
namespace E { public abstract class Test { private const int N = 1000000; private string name; public Test(string name) { this.name = name; } public abstract int CountChar(string s, char c); public void DoTest() { int nc = 0; long t1 = DateTime.Now.Ticks; for(int i = 0; i < N; i++) { nc = CountChar("Dette er en test", 'e'); } long t2 = DateTime.Now.Ticks; Console.WriteLine(String.Format("{0,-15} : {1,10} ({2})", name, (t2 - t1), nc)); } } public class TestForLoop : Test { public TestForLoop() : base("for loop") { } public override int CountChar(string s, char c) { int res = 0; for(int i = 0; i < s.Length; i++) { if(s[i] == c) { res++; } } return res; } } public class TestSplit : Test { public TestSplit() : base("Split") { } public override int CountChar(string s, char c) { return (s.Split(c).Length - 1); } } public class TestRegex : Test { public TestRegex() : base("Regex") { } public override int CountChar(string s, char c) { Regex r = new Regex("" + c); return r.Matches(s).Count; } } public class TestRegexFixed : Test { private static Regex r = new Regex("e", RegexOptions.Compiled); public TestRegexFixed() : base("Regex fixed") { } public override int CountChar(string s, char c) { return r.Matches(s).Count; } } public class TestClass { public static void Main(string[] args) { (new TestForLoop()).DoTest(); (new TestSplit()).DoTest(); (new TestRegex()).DoTest(); (new TestRegexFixed()).DoTest(); } } }
Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.