PDA

View Full Version : The fastest way to detect same char's in string


umen
11-09-2002, 02:03 PM
hello
i was wandering what is the best/fastest way to get the count of particular char in astring
something like if i have the string : "|blah||blah|" .and i like to get the count of the char "|"
in the string (that is 4 in this case ) do i need to loop the string something like this:
for(var i=0;i< szFoo.length ;i++){
if(szFoo.charAt(i)=='|')
iTmpLevelCount++;
}
or i can get it faster with RegExp or something ...
thanks!

Borgtex
11-09-2002, 02:15 PM
a="|blah||blah|"
count=a.split('|').length-1
alert(count)

jkd
11-09-2002, 02:32 PM
I'm pretty sure using a for loop is technically faster than the split() method. You have n steps to search through the array using a for loop.

With split, you have the same n-steps (implemented within the browser), then taking substrings and loading them into an array.

Since you're using Javascript though, this really isn't a critical performance kinda deal, so either will probably suit you fine.

Borgtex
11-09-2002, 03:40 PM
I'm pretty sure using a for loop is technically faster than the split() method. You have n steps to search through the array using a for loop.

I dont think so. Try this two functions in your address bar:

javascript:a=top.document.body.innerHTML.split('a').length-1;alert(a)

javascript:count=0;a=top.document.body.innerHTML;for (t=0;t<a.length;t++){if (a.charAt(t)=='a') count++};alert(count)

(without the space between java & script, of course)


the one using split is faster (if you can't see it, try with a large page of text). Also, with split, you can search for words or phrases without need to code anything else:

count=a.split('blah').length-1

or do a search & replace:

a=a.split('blah').join('BlAh')