Link to home
Start Free TrialLog in
Avatar of Blowfelt82
Blowfelt82

asked on

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?
Avatar of SubSun
SubSun
Flag of India image

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

Open in new window

Avatar of Blowfelt82
Blowfelt82

ASKER

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...
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
}

Open in new window

Unfortunately when I try that command I get a 'You must provide a value expression on the right-hand side of the '-' operator.
Then you probably have a space after a hyphen somewhere.  Select all the code above and paste and run.
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
ASKER CERTIFIED SOLUTION
Avatar of SubSun
SubSun
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Good call, I am using powershell v1.0.0.0 - your final solution worked like a charm. Thanks for the help! Perhaps its time I move onto the latest version of powershell!