[英]Function to Make Pascal Case? (C#)
我需要一個帶字符串和“pascal case”的函數。 新單詞開始的唯一指標是下划線。 以下是一些需要清理的示例字符串:
我開始研究一個使第一個字符為大寫的函數:
public string FirstCharacterUpper(string value)
{
if (value == null || value.Length == 0)
return string.Empty;
if (value.Length == 1)
return value.ToUpper();
var firstChar = value.Substring(0, 1).ToUpper();
return firstChar + value.Substring(1, value.Length - 1);
}
上面的函數沒有做的是刪除下划線和“ToUpper”字符右下角。
此外,任何有關如何使用沒有任何指標(如下划線)的字符串的概念。 例如:
這里的主要挑戰是確定一個詞的結束和另一個詞的開始。 我想我需要某種查找字典來確定新單詞的起源位置? 我們那里有圖書館可以做這種事嗎?
謝謝,
保羅
您可以使用TextInfo.ToTitleCase方法,然后刪除'_'字符。
所以,使用我得到的擴展方法:
http://theburningmonk.com/2010/08/dotnet-tips-string-totitlecase-extension-methods
你可以做點什么:
var s = "price_old";
s.ToTitleCase().Replace("_", string.Empty);
那么第一件事很簡單:
string.Join("", "price_old".Split(new [] { '_' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Substring(0, 1).ToUpper() + s.Substring(1)).ToArray());
返回PriceOld
第二件事情更難。 由於companysource
可能是CompanySource
或者CompanysOurce
,因此可以自動化但是非常錯誤。 你需要一本英文字典 ,然后做一些猜測(好吧,我的意思是很多 )哪個詞的組合是正確的。
嘗試這個:
public static string GetPascalCase(string name)
{
return Regex.Replace(name, @"^\w|_\w",
(match) => match.Value.Replace("_", "").ToUpper());
}
Console.WriteLine(GetPascalCase("price_old")); // => Should be PriceOld
Console.WriteLine(GetPascalCase("rank_old" )); // => Should be RankOld
帶下划線:
s = Regex.Replace(s, @"(?:^|_)([a-z])",
m => m.Groups[1].Value.ToUpper());
沒有下划線:
你自己在那里。 但是繼續搜索; 如果沒有人這樣做過,我會感到驚訝。
對於你分裂串聯單詞的第二個問題,你可以利用我們最好的朋友Google&Co。如果你的連接輸入由通常的英語單詞組成,搜索引擎對單個單詞的命中率很高,作為另一個搜索查詢
如果您輸入樣本輸入,Google和Bing會建議以下內容:
original | Google | Bing
=====================================================================
companysource | company source | company source
financialtrend | financial trend | financial trend
accountingchangetype | accounting changetype | accounting change type
看到這個例子 。
為此編寫一個小屏幕刮刀應該相當容易。
對於那些需要非正則表達式解決方案的人
public static string RemoveAllSpaceAndConcertToPascalCase(string status)
{
var textInfo = new System.Globalization.CultureInfo("en-US").TextInfo;
var titleCaseStr = textInfo.ToTitleCase(status);
string result = titleCaseStr.Replace("_","").Replace(" ", "");
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.