Quick tip: Convert to Title Case

Most people know how to convert a string to all upper case or all lower case. In this quick tip, I’ll show you how to use ‘TextInfo’ to convert a string to Title Case.

$string = 'test string'
[System.Threading.Thread]::CurrentThread.CurrentCulture.TextInfo.ToTitleCase($string)

As you see if you test it out your self, it will output ‘Test String’. The ToTitleCase method will capitalize all words in the string.

If, on the other hand, you would like to only capitalize the first word in a sentence, the following small function might come in handy:


function Out-CapitalizedString {
param([string]$String)
if(-not([System.String]::IsNullOrEmpty($String))) {
foreach ($sentence in ($String.Split('.'))) {
if(-not([System.String]::IsNullOrEmpty($sentence))) {
$sentence = $sentence.Trim()
[array]$outputString += [char]::ToUpper($sentence[0]) + $sentence.Substring(1)
}
else {
[array]$outputString += $sentence
}
}
Write-Output ($outputString -join '. ').Trim()
}
}

2 comments

Leave a comment