2011-04-14 87 views
0

我試圖找到一種有效的方法來接收輸入字符串並在每個標點符號(. : ? !)之後加上一個空格後面的第一個字母。C#大寫字符串,但僅限於某些標點符號

輸入:

「我吃的東西,但我沒有。。?! 代替,沒有你怎麼想我不 想請問me.moi」

輸出:

「我吃的東西,但是我沒有。。?! 相反,沒有你怎麼想我不 想請問me.moi」

顯而易見的是將它分開,然後大寫每個組的第一個字符,然後連接一切。但它很醜陋。什麼是最好的方法來做到這一點? (我想Regex.Replace使用MatchEvaluator大寫的第一個字母,但想獲得更多的想法)

謝謝!

+0

我會與分裂的想法走。這是一個好主意,正則表達式將會變得更加醜陋。另外,作爲一般規則,它通常更好地使用字符串操作,而不是正則表達式。 – 2011-04-14 13:56:40

回答

2

試試這個:

string expression = @"[\.\?\!,]\s+([a-z])"; 
string input = "I ate something. but I didn't: instead, no. what do you think? i think not! excuse me.moi"; 
char[] charArray = input.ToCharArray(); 
foreach (Match match in Regex.Matches(input, expression,RegexOptions.Singleline)) 
{ 
    charArray[match.Groups[1].Index] = Char.ToUpper(charArray[match.Groups[1].Index]); 
} 
string output = new string(charArray); 
// "I ate something. But I didn't: instead, No. What do you think? I think not! Excuse me.moi" 
+0

在他的例子'對不起.Moi'應該是'對不起.moi'用小寫字母moi – w69rdy 2011-04-14 14:09:22

+0

固定。所以空間是強制性的。 – Aliostad 2011-04-14 14:10:35

+0

需要從char類中刪除逗號,並且不需要轉義那些字符:即'@「[。?!] \ s +([a-z])」' – ridgerunner 2011-04-14 20:35:38

0

使用正則表達式/ MatchEvaluator路線,你可以匹配

"[.:?!]\s[a-z]" 

和把握整場比賽。

4

方便快捷:

static class Ext 
{ 
    public static string CapitalizeAfter(this string s, IEnumerable<char> chars) 
    { 
     var charsHash = new HashSet<char>(chars); 
     StringBuilder sb = new StringBuilder(s); 
     for (int i = 0; i < sb.Length - 2; i++) 
     { 
      if (charsHash.Contains(sb[i]) && sb[i + 1] == ' ') 
       sb[i + 2] = char.ToUpper(sb[i + 2]); 
     } 
     return sb.ToString(); 
    } 
} 

用法:

string capitalized = s.CapitalizeAfter(new[] { '.', ':', '?', '!' }); 
+0

+1比正則表達式更容易閱讀(對我們凡人來說)。 – 2011-04-14 14:24:46

2

我使用的擴展方法。

public static string CorrectTextCasing(this string text) 
{ 
    // /[.:?!]\\s[a-z]/ matches letters following a space and punctuation, 
    // /^(?:\\s+)?[a-z]/ matches the first letter in a string (with optional leading spaces) 
    Regex regexCasing = new Regex("(?:[.:?!]\\s[a-z]|^(?:\\s+)?[a-z])", RegexOptions.Multiline); 

    // First ensure all characters are lower case. 
    // (In my case it comes all in caps; this line may be omitted depending upon your needs)   
    text = text.ToLower(); 

    // Capitalize each match in the regular expression, using a lambda expression 
    text = regexCasing.Replace(text, s => (s.Value.ToUpper)); 

    // Return the new string. 
    return text; 

} 

然後,我可以做到以下幾點:

string mangled = "i'm A little teapot, short AND stout. here IS my Handle."; 
string corrected = s.CorrectTextCasing(); 
// returns "I'm a little teapot, short and stout. Here is my handle." 
相關問題