Last active
July 23, 2024 19:43
-
-
Save B-Art/b101b1e048db63822737afefc7ccd9be to your computer and use it in GitHub Desktop.
#Powershell #Pwsh #Core `Chop String into choosen lengths Positive from Begin to End, Negative from End to Begin.`
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
using namespace System.Runtime.CompilerServices | |
# Define the type extension for the System.String class | |
class StringExtensions { | |
[Extension()] | |
static [String[]] Chop([String]$Value) { | |
return [StringExtensions]::Chop($Value, 2) | |
} | |
static [String[]] Chop([String]$Value, [int]$Length) { | |
if ($Length -eq 0) { | |
throw 'Length cannot be zero.' | |
} | |
$Result = [System.Collections.Generic.List[string]]::new() | |
if ($Length -lt 0) { | |
$Length = [int]::Abs($Length) | |
if ($Value.Length % $Length -gt 0) { | |
$Result.Add($Value.Substring(0, ($Value.Length % $Length))) | |
$Value = $Value.Substring(($Value.Length % $Length)) | |
} | |
} | |
while (![string]::IsNullOrEmpty($Value)) { | |
if ($Length -le $Value.Length) { | |
# Chopping from beginning to end | |
$Result.Add($Value.Substring(0, $Length)) | |
$Value = $Value.Substring($Length) | |
} else { | |
$Result.Add($Value) | |
$Value = $null | |
} | |
} | |
return $Result | |
} | |
} | |
# Example usage | |
$string = 'PowerShellIsGreat' | |
# Use the Chop method with positive length (chop from beginning) | |
$positiveChop = [StringExtensions]::Chop($string, 5) | |
Write-Output $positiveChop | |
# Use the Chop method with negative length (chop from end) | |
$negativeChop = [StringExtensions]::Chop($string, -5) | |
Write-Output $negativeChop |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment