Created
September 26, 2024 21:59
-
-
Save Calvindd2f/da8c0bce3c217fc3f72ac13566fe2fbe to your computer and use it in GitHub Desktop.
Class for slicing string similar to Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class StringSlicer { | |
| [string]$StringValue | |
| StringSlicer([string]$initialValue) { | |
| $this.StringValue = $initialValue | |
| } | |
| [string] Slice([int]$start, [int]$length) { | |
| if ($length -eq 0 -or $start -ge $this.StringValue.Length) { | |
| return '' | |
| } | |
| $substring = $this.StringValue.Substring($start, [math]::Min($length, $this.StringValue.Length - $start)) | |
| return $substring | |
| } | |
| } | |
| # Example : | |
| $slicer = [StringSlicer]::new("Hello, PowerShell!") | |
| $result = $slicer.Slice(7, 10) | |
| Write-Output $result # Output: PowerShell |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment