String startswith method

If you look at the methods available on a string one of them is StartsWith(). It tests if a given string starts with another string

£> ‘frgrughrugu’.StartsWith

OverloadDefinitions
——————-
bool StartsWith(string value)
bool StartsWith(string value, System.StringComparison comparisonType)
bool StartsWith(string value, bool ignoreCase, cultureinfo culture)

 

The first option is the easiest to use and the most common scenario

£> ‘frgrughrugu’.StartsWith(‘frg’)
True
£> ‘frgrughrugu’.StartsWith(‘xya’)
False

Unlike most things in PowerShell this comparison is NOT case insensitive

£> ‘frgrughrugu’.StartsWith(‘fRg’)
False

 

The second option helps by letting you use the members of the System.StringComparison enumeration to control the way the comparison is performed

£> $ct = [System.StringComparison]::CurrentCultureIgnoreCase

£> ‘frgrughrugu’.StartsWith(‘frg’, $ct)
True
£> ‘frgrughrugu’.StartsWith(‘fRg’, $ct)
True

 

The final option allows you to use a culture to control the way the comparison is performed. $null implies use the current culture. Note how the boolean controlling the case sensitivity works:

£> ‘frgrughrugu’.StartsWith(‘frg’, $true, $null)
True
£> ‘frgrughrugu’.StartsWith(‘fRg’, $true, $null)
True
£> ‘frgrughrugu’.StartsWith(‘fRg’, $false, $null)
False
£> ‘frgrughrugu’.StartsWith(‘frg’, $false, $null)
True

Advertisements
This entry was posted in Powershell Basics. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s