2013-07-23 34 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