Created
April 26, 2016 09:10
-
-
Save theunrepentantgeek/e768a6fd5af45712554440aca74d8706 to your computer and use it in GitHub Desktop.
Example wrap-string function
This file contains 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
# Word wrap function, return word wrapped version of passed string | |
function wrap-string($str, $length) | |
{ | |
if ($str.length -lt $length) | |
{ | |
return $str | |
} | |
# Holds the final version of $str with newlines | |
$strWithNewLines = "" | |
# current line, never contains more than screen width | |
$curLine = 0 | |
# Loop over the words and write a line out just short of window size | |
foreach ($word in $str.Split(" ")) | |
{ | |
# Lets see if adding a word makes our string longer then window width | |
if (($curLine + 1 + $word.length) -gt $length) | |
{ | |
# With the new word we've gone over width | |
# append newline before we append new word | |
$strWithNewLines += "`r`n" + $word | |
# Reset current line | |
$curLine = $word.length | |
} | |
else | |
{ | |
# Append word to current line and final str | |
if ($curLine -gt 0) | |
{ | |
$strWithNewLines += " " | |
} | |
$curLine += $word.Length + 1 | |
$strWithNewLines += $word | |
} | |
} | |
# return our word wrapped string | |
return $strWithNewLines | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment