C# 将字符串大写,但仅在某些标点符号之后

发布于 2024-10-31 23:09:58 字数 421 浏览 2 评论 0原文

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

输入:

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

输出:

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

显而易见的是,将其拆分,然后将每个组的第一个字符大写,然后连接所有内容。但这非常丑陋。执行此操作的最佳方法是什么?(我在想 Regex.Replace 使用 MatchEvaluator 将第一个字母大写,但希望获得更多想法)

谢谢!

I'm trying to find an efficient way to take an input string and capitalize the first letter after every punctuation mark (. : ? !) which is followed by a white space.

Input:

"I ate something. but I didn't:
instead, no. what do you think? i
think not! excuse me.moi"

Output:

"I ate something. But I didn't:
Instead, no. What do you think? I
think not! Excuse me.moi"

The obvious would be to split it and then capitalize the first char of every group, then concatenate everything. But it's uber ugly. What's the best way to do this? (I'm thinking Regex.Replace using a MatchEvaluator that capitalizes the first letter but would like to get more ideas)

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

半山落雨半山空 2024-11-07 23:09:58

快速简单:

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

Fast and easy:

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();
    }
}

Usage:

string capitalized = s.CapitalizeAfter(new[] { '.', ':', '?', '!' });
浅语花开 2024-11-07 23:09:58

试试这个:

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"

Try this:

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"
无风消散 2024-11-07 23:09:58

我使用扩展方法。

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

I use an extension method.

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;

}

Then I can do the following:

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."
桃气十足 2024-11-07 23:09:58

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

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

整个匹配并将其大写。

Using the Regex / MatchEvaluator route, you could match on

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

and capitalize the entire match.

为人所爱 2024-11-07 23:09:58

其中文本变量包含字符串

        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);
            }
        }

Where the text variable contains the string

        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);
            }
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文