Skip to content

Instantly share code, notes, and snippets.

@Calvindd2f
Created September 26, 2024 21:59
Show Gist options
  • Select an option

  • Save Calvindd2f/da8c0bce3c217fc3f72ac13566fe2fbe to your computer and use it in GitHub Desktop.

Select an option

Save Calvindd2f/da8c0bce3c217fc3f72ac13566fe2fbe to your computer and use it in GitHub Desktop.
Class for slicing string similar to Python
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