Monthly Archive

Categories

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

Comments are closed.