Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

how to count number of certain char within string

15,502 views
Skip to first unread message

Frank

unread,
Jul 16, 2008, 7:08:09 PM7/16/08
to
Hi,

If I have a variable string, ie:

$test="one,two,thr"

or

$test="one,two,thr,four,five"

What is the best way to find the number of "," in the string? index?

Thanks in advance,


Martin Zugec

unread,
Jul 16, 2008, 7:27:46 PM7/16/08
to
What about
"one,two,three".Split(",") | measure-object or ("one,two,three".Split(",") |
measure-object).Count to get integer?

Martin

"Frank" <Fr...@discussions.microsoft.com> wrote in message
news:6E711425-483C-4B06...@microsoft.com...

Kiron

unread,
Jul 16, 2008, 7:30:58 PM7/16/08
to
$test="one,two,thr,four,five"
 
$char = ','
$result = 0..($test.length - 1) | ? {$test[$_] -eq $char}
 
# how many?
$result.count
 
# indices
$result
 
# verify
$result | % {$test[$_]}

--
Kiron

Frank

unread,
Jul 16, 2008, 11:06:04 PM7/16/08
to
Why is the count always one more than it really is? There are 2 "," but the
count is 3.

Shay Levy [MVP]

unread,
Jul 17, 2008, 4:33:30 AM7/17/08
to

PS > [regex]::matches($test,",").count
4


---
Shay Levy
Windows PowerShell MVP
blog: http://blogs.microsoft.co.il/blogs/ScriptFanatic

F> Hi,
F>
F> If I have a variable string, ie:
F>
F> $test="one,two,thr"
F>
F> or
F>
F> $test="one,two,thr,four,five"
F>
F> What is the best way to find the number of "," in the string? index?
F>
F> Thanks in advance,
F>


Karl Mitschke

unread,
Jul 17, 2008, 9:58:12 AM7/17/08
to
Hello Frank,

The count starts at 0.

The first object is 0
The second is 1
On and on :)

Karl Mitschke

unread,
Jul 17, 2008, 10:06:32 AM7/17/08
to
ACK - Should have read the question better - sorry :)

What are you actually counting?

In

"one,two,three".Split(",") | measure-object

You are splitting on the "," - so, there are three itens, one, two, and three.

If your requirements are really this simple (the number of commas in a string)
you would have to take the output and subtract 1 like

("one,two,three".Split(",") |measure-object).Count -1

Karl

Roman Kuzmin

unread,
Jul 17, 2008, 12:17:32 PM7/17/08
to
Performance remark. Using of Measure-Object is redundant - Split() returns
an array, property Count perfectly works for it:

"one,two,three".Split(",").Count - 1

--
Thanks,
Roman Kuzmin

http://code.google.com/p/farnet/
PowerShell and .NET in FAR Manager

Karl Mitschke

unread,
Jul 17, 2008, 3:33:49 PM7/17/08
to
Hello Roman,

An excellent point - I should not created my own example for the OP instead
of copying :)

Thanks

Karl

> Performance remark. Using of Measure-Object is redundant - Split()
> returns an array, property Count perfectly works for it:
>
> "one,two,three".Split(",").Count - 1
>

0 new messages