.NET方法将字符串转换为句子大小写

Lia*_*amB 25 c# string sentencecase

我正在寻找一个函数来将UpperCase中的一串文本转换为SentenceCase.我能找到的所有例子都将文本转换为TitleCase.

一般意义上的句子案例描述了在句子中使用大写的方式.句子案例还描述了英语句子的标准大写,即句子的第一个字母大写,其余为小写(除非因特定原因需要大写,例如专有名词,首字母缩略词等).

有人能指出我对SentenceCase的脚本或函数的方向吗?

LBu*_*kin 36

.NET没有内置任何东西 - 但是,这是正则表达式处理实际上可以正常工作的情况之一.我首先将整个字符串转换为小写,然后,作为第一个近似,您可以使用正则表达式来查找所有序列[a-z]\.\s+(.),并用于ToUpper()将捕获的组转换为大写.的RegEx类有一个重载Replace()方法,其接受一个MatchEvaluator代表,它允许定义如何更换匹配的值.

以下是这个工作的代码示例:

var sourcestring = "THIS IS A GROUP. OF CAPITALIZED. LETTERS.";
// start by converting entire string to lower case
var lowerCase = sourcestring.ToLower();
// matches the first sentence of a string, as well as subsequent sentences
var r = new Regex(@"(^[a-z])|\.\s+(.)", RegexOptions.ExplicitCapture);
// MatchEvaluator delegate defines replacement of setence starts to uppercase
var result = r.Replace(lowerCase, s => s.Value.ToUpper());

// result is: "This is a group. Of uncapitalized. Letters."
Run Code Online (Sandbox Code Playgroud)

这可以通过多种不同的方式进行改进,以更好地匹配更广泛的句型(不仅仅是以字母+句号结尾的那些).


Ed *_*d B 7

这适合我.

/// <summary>
/// Converts a string to sentence case.
/// </summary>
/// <param name="input">The string to convert.</param>
/// <returns>A string</returns>
public static string SentenceCase(string input)
{
    if (input.Length < 1)
        return input;

    string sentence = input.ToLower();
    return sentence[0].ToString().ToUpper() +
       sentence.Substring(1);
}
Run Code Online (Sandbox Code Playgroud)

  • "点作为分隔符"并没有真正削减它.`先生 史密斯太太每人1000美元; 他们住在Magnolia Blvd. 在蓝色的房子里 (2认同)

小智 5

有一个内置ToTitleCase()功能,将来会扩展以支持多种文化。

来自MSDN的示例:

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] values = { "a tale of two cities", "gROWL to the rescue",
                          "inside the US government", "sports and MLB baseball",
                          "The Return of Sherlock Holmes", "UNICEF and children"};

      TextInfo ti = CultureInfo.CurrentCulture.TextInfo;
      foreach (var value in values)
         Console.WriteLine("{0} --> {1}", value, ti.ToTitleCase(value));
   }
}
// The example displays the following output:
//    a tale of two cities --> A Tale Of Two Cities
//    gROWL to the rescue --> Growl To The Rescue
//    inside the US government --> Inside The US Government
//    sports and MLB baseball --> Sports And MLB Baseball
//    The Return of Sherlock Holmes --> The Return Of Sherlock Holmes
//    UNICEF and children --> UNICEF And Children
Run Code Online (Sandbox Code Playgroud)

尽管它通常很有用,但它有一些重要的限制:

通常,标题大小写将单词的第一个字符转换为大写,其余字符转换为小写。但是,此方法当前未提供适当的大小写来转换完全为大写的单词,例如首字母缩写词。下表显示了该方法呈现多个字符串的方式。

...该ToTitleCase方法提供了任意的套管行为,但不一定在语言上是正确的。语言正确的解决方案将需要其他规则,并且当前算法稍微更简单,更快速。我们保留将来使该API变慢的权利。

来源:http//msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx

  • 但是标题大小写与句子大小写不同 (4认同)