2013-07-23 31 views
1

我需要大寫每個單詞的第一個字母使用拆分加入使用PowerShell 3.0PowerShell 3字符串操作使用拆分和加入

我一直在瘋狂試圖找出這一點。

任何幫助,將不勝感激。

Function Proper([switch]$AllCaps, [switch]$title, [string]$textentered=" ") 
{ 
    if ($AllCaps) 
     {$textentered.Toupper()} 
    Elseif ($title) 
     {$textentered -split " " 

     $properwords = $textentered | foreach { $_ } 


      $properwords -join " " 
      $properwords.substring(0,1).toupper()+$properwords.substring(1).tolower() 

      } 
} 
proper -title "test test" 

回答

2

System.Globalization.TextInfo類有ToTitleCase方法可以使用,只是加入你的話是正常轉換成字符串(稱爲$lowerstring爲例)然後調用使用`獲取文化cmdlet的::

該字符串的方法
$titlecasestring = (Get-Culture).TextInfo.ToTitleCase($lowerstring) 

對於字符串連接我傾向於使用以下格式:

$lowerstring = ("the " + "quick " + "brown " + "fox") 

但下面也v alid:

$lowerstring = 'the','quick','brown','fox' -join " " 

$lowerstring = $a,$b,$c,$d -join " " 

編輯:

根據您提供的代碼,你並不需要拆分/加入字符串,如果你正在傳遞的只是一個字符串一個短語,所以以下是你需要什麼

Function Proper{ 
    Param ([Parameter(Mandatory=$true, Position=0)] 
      [string]$textentered, 
      [switch]$AllCaps, 
      [switch]$Title) 

    if ($AllCaps){$properwords = $textentered.Toupper()} 

    if ($title) { 
       $properwords = (Get-Culture).TextInfo.ToTitleCase($textentered) 
       } 

    if ((!($Title)) -and (!($AllCaps))){ 
     Return $textentered} 
} 

Proper "test test" -AllCaps 
Proper "test test" -Title 
Proper "test test" 

Param()塊我設置$ textentered參數作爲強制性的,並且它必須是第一個參數(位置= 0)。

如果沒有傳遞AllCaps或Title參數,則原始輸入字符串會被傳回,不會改變。

+0

感謝您的意見。這是我想出的。它只是大寫第一個單詞的第一個字母。函數正確([開關] $ ALLCAPS,[開關] $標題,[字符串] $ textentered =」「){ \t如果($ ALLCAPS) \t \t {$ textentered.Toupper()} \t ELSEIF($標題) \t \t {$ textentered -split「」 \t \t $ properwords = $ textentered |的foreach {$ _} \t \t $ properwords -join 「」 $ properwords.substring(0,1).toupper()+ $ properwords.substring(1).tolower() \t \t } } proper -title「test test」 – user2608870