2011-04-14 93 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." 
相关问题