# Split a number into its composite digits and count.

I am looking for a way to count the digits that comprise a number - for example...

345 = 3 + 4 + 5 = 12

I have tried a few techniques to do this with Powershell, but all my solutions end up using the ASCII character code value of the digit rather than the actual number itself. I'm sure there must be a very easy way of achieving this?
###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
Try..
``````\$Num = "345"
(\$num -split "" | Measure -Sum).Sum
``````
0
Author Commented:
Doesnt seem to work, I have the following...

for(\$i = 1; \$i -lt 100; \$i++) {
\$current = "\$i"
(\$current.Split("") | Measure-Object -Sum).Sum
}

But this isnt returning the results I would expect...

Note: I had to use \$current.Split("") to make the code compile...
0
Commented:
Use the -split operator as Subsun posted, not the split method.
``````for(\$i = 1; \$i -lt 100; \$i++) {
\$current = \$i
(\$current -Split "" | Measure-Object -Sum).Sum
}
``````
0
Author Commented:
Unfortunately when I try that command I get a 'You must provide a value expression on the right-hand side of the '-' operator.
0
Commented:
Then you probably have a space after a hyphen somewhere.  Select all the code above and paste and run.
0
Author Commented:
I think it must be something more sinister... I copied and pasted the following into a new window...

\$num = "345"
(\$num -split "" | Measure -Sum).Sum

And am still getting the same issue?

EXCEPTION TYPE: System.Management.Automation.ParseException
MESSAGE: You must provide a value expression on the right-hand side of the '-' operator.
POSITION: At line:2 char:8 (\$num -s <<<< plit "" | Measure -Sum).Sum
0
Commented:
Which version of PowerShell?

In PowerShell console type \$host.Version and find out the version..

you need to have at least PS V.2 to use -split operator..

If it is version V.1 then you can try..
``````for(\$i = 1; \$i -lt 100; \$i++) {
\$current = "\$i"
([regex]::split(\$current,"") | Measure-Object -Sum).Sum
}
``````
0

Experts Exchange Solution brought to you by