0

. : ? !入力文字列を取得し、空白が続くすべての句読点 ( ) の後の最初の文字を大文字にする効率的な方法を見つけようとしています。

入力:

「私は何かを食べました.しかし、私は食べませんでした:代わりに、いや.あなたはどう思いますか?私はそうは思いません!すみません.moi.moi」

出力:

「私は何かを食べました。しかし、私は食べませんでした:代わりに、いいえ。あなたはどう思いますか?私はそうは思いません!すみません.moi」

明らかなのは、それを分割してから、すべてのグループの最初の文字を大文字にしてから、すべてを連結することです。しかし、それは非常に醜いです。これを行う最善の方法は何ですか?(最初の文字を大文字にする a をRegex.Replace使用することを考えてMatchEvaluatorいますが、より多くのアイデアを得たいと考えています)

ありがとう!

4

5 に答える 5

6

素早く簡単:

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[] { '.', ':', '?', '!' });
于 2011-04-14T14:05:47.683 に答える
3

これを試して:

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"
于 2011-04-14T14:01:41.847 に答える
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."
于 2011-05-17T14:37:27.060 に答える
1

Regex / MatchEvaluatorルートを使用すると、

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

試合全体を大文字にします。

于 2011-04-14T13:59:04.190 に答える