首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C#大写字符串,但只在某些标点符号之后

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

Stack Overflow用户
提问于 2011-04-14 13:51:34
回答 5查看 4.8K关注 0票数 0

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

输入:

“我吃了些东西,但我没有:相反,不。你觉得怎么样?我想没有!对不起me.moi”

输出:

“我吃了些东西,但我没有:相反,不。你觉得怎么样?我想不是!原谅me.moi”

显而易见的是,将其分割,然后将每个组的第一个字符大写,然后将所有内容连接起来。但这太丑了。做这件事最好的方法是什么?(我认为Regex.Replace使用的是MatchEvaluator,它将第一个字母大写,但希望得到更多的想法)

谢谢!

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-04-14 14:01:41

试试这个:

代码语言:javascript
运行
复制
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"
票数 3
EN

Stack Overflow用户

发布于 2011-04-14 14:05:47

快速而容易:

代码语言:javascript
运行
复制
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();
    }
}

使用:

代码语言:javascript
运行
复制
string capitalized = s.CapitalizeAfter(new[] { '.', ':', '?', '!' });
票数 6
EN

Stack Overflow用户

发布于 2011-05-17 14:37:27

我使用扩展方法。

代码语言:javascript
运行
复制
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;

}

然后我可以做以下几件事:

代码语言:javascript
运行
复制
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."
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5664286

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档