字符串中的大写单词使用C# [英] Capitalizing words in a string using c#

查看:111
本文介绍了字符串中的大写单词使用C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个字符串,它利用的话。有些词(中,在等),都没有资本化,如果遇到被更改为小写。第一个词应该总是大写。最后的名字,如McFly的是不是在目前的范围,所以,同样的规则将适用于它们 - 仅首字母大写

I need to take a string, and capitalize words in it. Certain words ("in", "at", etc.), are not capitalized and are changed to lower case if encountered. The first word should always be capitalized. Last names like "McFly" are not in the current scope so the same rule will apply to them - only first letter capitalized.

例如:小鼠和人的通过CNN通过CNN应改为人鼠之间。 (因此ToTitleString不会在这里工作

For example: "of mice and men By CNN" should be changed to "Of Mice and Men by CNN". (Therefore ToTitleString won't work here)

我不知道什么是做到这一点的最好办法。
我想到了什么,是由空格分割的字符串,每个字去了,如果有必要改变它,它串联到前一个字,等。
似乎很天真,我想知道是否有更好的方式来做到这一点,使用.net 3.5。

I'm wondering what would be the best way to do that. What I thought of is to split the string by spaces, and go over each word, changing it if necessary, and concatenating it to the previous word, and so on. It seems pretty naive and I was wondering if there's a better way to do it, using .Net 3.5.

推荐答案

根据你打算做资本我会用天真的方法去多久。 。你可能用正则表达式做,但事实上,你不希望某些字大写,使这有点棘手

Depending on how often you plan on doing the capitalization I'd go with the naive approach. You could possibly do it with a regular expression, but the fact that you don't want certain words capitalized makes that a little trickier.

编辑:

您可以使用正则表达式两遍做

You can do it with two passes using regexes

var result = Regex.Replace("of mice and men isn't By CNN", @"\b(\w)", m => m.Value.ToUpper());
result = Regex.Replace(result, @"(\s(of|in|by|and)|\'[st])\b", m => m.Value.ToLower(), RegexOptions.IgnoreCase);

这输出小鼠和人通过CNN

第一个表达式大写一个字边界上每一个字母,第二个downcases任何文字匹配由空格包围名单。

The first expression capitalizes every letter on a word boundary and the second one downcases any words matching the list that are surrounded by whitespace.

的缺点这种方法是,你正在使用regexs(现在你有两个问题),你需要不断的排除单词列表保持最新状态。我正则表达式福不够好,能够做到这一点的一种表现,但也可能是可行的。

The downsides to this approach is that you're using regexs (now you have two problems) and you'll need to keep that list of excluded words up to date. My regex-fu isn't good enough to be able to do it in one expression, but it might be possible.

这篇关于字符串中的大写单词使用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆