Home > Blockchain >  Write to array every 4 characters
Write to array every 4 characters

Time:10-13

I have a string "1111222233334444" with numbers, how to make an array out of it, "1111", "2222", "3333", "4444".

i want a 4 character instance to be instantiated, how is it implemented in powershell?

CodePudding user response:

Simple loop would be enough:

$s = '1111222233334444'
$i = 0; while ($i -lt ($s.Length-3)/4) { $s.Substring($i*4, 4); $i  ; }

(Length-3)/4 is for unaligned blocks of 4. Example: If string is 1111222 it gives (7-3)/4=1 full items.


In addition to comment by Olaf, another way is to use Regex. But, instead of using capturing groups and filtering:

$s -split "(....)" -ne ""

I would use:

[Regex]::Matches($s, "\d{4}").Value

Which seems more natural and readable.

  • Related