【问题标题】:C# Capitalizing string, but only after certain punctuation marksC#大写字符串,但仅在某些标点符号之后
【发布时间】:2011-04-14 13:51:34
【问题描述】:

我正在尝试找到一种有效的方法来获取输入字符串并将每个标点符号 (. : ? !) 后跟一个空格的第一个字母大写。

输入:

“我吃了点东西。但我没有: 相反,没有。你怎么看?一世 不认为!对不起.moi”

输出:

“我吃了点东西。但我没有: 相反,没有。你怎么看?一世 不认为!对不起.moi”

显而易见的是拆分它,然后将每个组的第一个字符大写,然后连接所有内容。但它超级丑陋。最好的方法是什么? (我在想Regex.Replace 使用MatchEvaluator 将第一个字母大写但想获得更多想法)

谢谢!

【问题讨论】:

  • 我会同意拆分的想法。这是一个好主意,而正则表达式将变得更加丑陋。此外,作为一般规则,如果可以,通常最好使用字符串操作而不是正则表达式。

标签: c# .net regex capitalization


【解决方案1】:

快速简单:

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[] { '.', ':', '?', '!' });

【讨论】:

  • +1 比正则表达式更容易阅读(无论如何对于我们凡人来说)。
【解决方案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"

【讨论】:

  • 在他的示例中,'Excuse me.Moi' 应该是带有小写 moi 的 'Excuse me.moi'
  • 需要从 char 类中删除逗号,并且不需要转义这些字符:即@"[.?!]\s+([a-z])"
【解决方案3】:

我使用扩展方法。

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."

【讨论】:

    【解决方案4】:

    使用 Regex / MatchEvaluator 路由,您可以匹配

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

    并将整个匹配大写。

    【讨论】:

      【解决方案5】:

      文本变量包含字符串的地方

              string text = "I ate something. but I didn't: instead, no. what do you think? i think not! excuse me.moi";
              string[] punctuators = { "?", "!", ",", "-", ":", ";", "." };
              for (int i = 0; i< 7;i++)
              {
                  int pos = text.IndexOf(punctuators[i]);
                  while(pos!=-1)
                  {
                      text = text.Insert(pos+2, char.ToUpper(text[pos + 2]).ToString());
                      text = text.Remove(pos + 3, 1);
                      pos = text.IndexOf(punctuators[i],pos+1);
                  }
              }
      

      【讨论】:

        猜你喜欢
        • 2011-11-30
        • 1970-01-01
        • 2018-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多