A nice easy one I though, but it's getting prickly.
I have a string, say:
$a = "ThisIsMyString"
I want to be able to enumerate through it and test if the character is
a capital or not. There's a method on MSDN called IsUpper, but either
PowerShell haven't implemented it, or I'm just missing the point -
either is possible ;)
for ($i=0; $ -lt $a.length; $i++)
{
# Check if the char is uppercase?
<insert cool line here>
}
I did consider testing against the ASCII value. Capital characters run
from 65-90. I noticed that you can happily cast:
[char]65 and it will return "A". However I wasn't able to find a way
to cast the other way around?
[int]"A" caused an error for example.
Any constructive ideas anyone?
Cheers
Adam
To get at the char from within your loop try $c = $a.Chars(0)
That gets you the System.Char, but note that IsUpper is a static
member so to call it, use:
[char]::IsUpper($c)
rather than
$c.IsUpper()
HTH,
Duncan.
Ofcourse, that should be $i not 0, so you could do the whole thing as:
[char]::IsUpper($a.Chars($i))
The Get-Member cmdlet doesn't seem to list the static members of a
type - I wonder how you can find out about them from within the CLI?
Thanks,
Duncan.
Many thanks for the speedy and accurate response.
This worked a treat. :)
As I'm not actually a programmer type (though I can see this
changing), I will have to look into static members in more depth, as I
am finding quite a lot is not readily visible within PowerShell. At
this stage, you need to be quite handy at ferreting out the "secret
knowledge"!
Cheers
Adam
No problem. A static member (also known as a 'shared' in vb.net)
unlike normal class members is only created once for all instances of
an object.
Suppose you're writing some software for a bank and you create a class
called account. You'll create an instance of account for each
customer and naturally you'd want members such as balance, name,
account number to be created for each instance also. So Fred Perry
may have a balance of £500 but Janet Smith has a balance of £1000 -
they're different.
Now suppose you want to keep a track of how many accounts the bank has
open. No problem, create the _numberOfAccounts member as static.
This instructs the compiler to only create one instance of
_numberOfAccounts and share it for all bank account objects.
Now get the constructor of the account class to increment the static
count member, and you can find out how many accounts are open at any
time just by querying the class (you don't need a specific instance of
a class to do this)
CBankAccount::_numberOfAccounts // returns 5, or 10 or whatever.
You can also have static functions (which is what IsUpper() is ).
These functions can be called without having a specific instance of a
class either, but they can only operate on static members, which is
why you have to supply the character to IsUpper.
Have a look at this wikipedia page:
http://en.wikipedia.org/wiki/Static_variable#Static_Variables_as_Class_Variables
Regards,
Duncan.