[dba-VB] Count a character in a string

Gustav Brock Gustav at cactus.dk
Sun Apr 13 04:47:21 CDT 2008


Hi Shamil

Neat! I'll add that to my toolbox.

/gustav

>>> shamil at users.mns.ru 13-04-2008 11:26 >>>
Hi All,

I have also tried:

string s = "asdf|qwert|zxcv|mnbv";
Regex rx = new Regex("|");
int count = rx.Matches(s).Count;  

and I (expectedly) found that it takes ages comparing with the first method:


string s = "asdf|qwert|zxcv|mnbv";
int count = 0;
for (int index = 0; index < s.Length; index++) 
  if ((s[index] ^ '|') == 0) count++;

which finished 20 million iterations in 3 sec, and I cancelled the RegEx
based test after several minutes waiting that it finishes for 20 million
iterations...

--
Shamil
 

-----Original Message-----
From: dba-vb-bounces at databaseadvisors.com 
[mailto:dba-vb-bounces at databaseadvisors.com] On Behalf Of Shamil
Salakhetdinov
Sent: Sunday, April 13, 2008 6:30 AM
To: 'Discussion concerning Visual Basic and related programming issues.'
Subject: Re: [dba-VB] Count a character in a string

Hi John,

My bet that this code will be the most speedy in .NET (C# sample):

int count = 0;
for (int index = 0; index < s.Length; index++) 
  if ((s[index] ^ '|') == 0) count++;

--
Shamil
 

-----Original Message-----
From: dba-vb-bounces at databaseadvisors.com 
[mailto:dba-vb-bounces at databaseadvisors.com] On Behalf Of jwcolby
Sent: Sunday, April 13, 2008 12:24 AM
To: VBA
Subject: [dba-VB] Count a character in a string

I do a lot of CSV stuff.  One of my file suppliers gives me files that 
throw an error when I try to import them and so I am writing tools to 
try and troubleshoot these files.  I need to be able to count the times 
that the field separator character is contained in a line.  The error I 
am getting says the line is too long but I have determined that is not 
the case.  I suspect that perhaps the field separator character is in 
the line too often.

So, if I have a line that looks like:

asdf|qwert|zxcv|mnbv

Other than just iterating through the string character by character, is 
there a way to get a count of the | character in the string?
-- 
John W. Colby
www.ColbyConsulting.com 
_______________________________________________
dba-VB mailing list
dba-VB at databaseadvisors.com 
http://databaseadvisors.com/mailman/listinfo/dba-vb 
http://www.databaseadvisors.com 

_______________________________________________
dba-VB mailing list
dba-VB at databaseadvisors.com 
http://databaseadvisors.com/mailman/listinfo/dba-vb 
http://www.databaseadvisors.com 

_______________________________________________
dba-VB mailing list
dba-VB at databaseadvisors.com 
http://databaseadvisors.com/mailman/listinfo/dba-vb 
http://www.databaseadvisors.com 






More information about the dba-VB mailing list