使用 C# 将字符串中的单词大写

发布于 2024-10-05 01:09:07 字数 336 浏览 0 评论 0原文

我需要一个字符串,并将其中的单词大写。某些单词(“in”、“at”等)不是大写的,如果遇到,则会更改为小写。第一个单词应始终大写。像“McFly”这样的姓氏不在当前范围内,因此相同的规则将适用于它们 - 仅首字母大写。

例如:“of mouse and men By CNN”应改为“Of Mice and Men by CNN”。 (因此 ToTitleString 在这里不起作用。)

最好的方法是什么?

我想用空格分割字符串,然后检查每个单词,必要时进行更改,然后将其连接到前一个单词,等等。 这看起来很天真,我想知道是否有更好的方法来做到这一点。我正在使用.NET 3.5。

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.

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

What would be the best way to do that?

I thought of splitting 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. I am using .NET 3.5.

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

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

发布评论

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

评论(10

半衬遮猫 2024-10-12 01:09:53

您应该像您所描述的那样创建自己的函数。

You should create your own function like you're describing.

厌味 2024-10-12 01:09:39

最简单明显的解决方案(对于英语句子)是:

  • "sentence".Split(" ") 空格字符上的句子
  • 循环遍历每个项目
  • 将每个项目的第一个字母大写 - item [i][0].ToUpper()
  • 重新合并回以空格连接的字符串。
  • 用“.”重复此过程。和“,”使用该新字符串。

The easiest obvious solution (for English sentences) would be to:

  • "sentence".Split(" ") the sentence on space characters
  • Loop through each item
  • Capitalize the first letter of each item - item[i][0].ToUpper(),
  • Remerge back into a string joined on a space.
  • Repeat this process with "." and "," using that new string.
囚我心虐我身 2024-10-12 01:09:33

处理简单情况的一种不聪明的方法:

var s = "of mice and men By CNN";
var sa = s.Split(' ');
for (var i = 0; i < sa.Length; i++)
    sa[i] = sa[i].Substring(0, 1).ToUpper() + sa[i].Substring(1);
var sout = string.Join(" ", sa);
Console.WriteLine(sout);

A non-clever approach that handles the simple case:

var s = "of mice and men By CNN";
var sa = s.Split(' ');
for (var i = 0; i < sa.Length; i++)
    sa[i] = sa[i].Substring(0, 1).ToUpper() + sa[i].Substring(1);
var sout = string.Join(" ", sa);
Console.WriteLine(sout);
思念满溢 2024-10-12 01:09:28

您可以拥有一个包含您想要忽略的单词的字典,将句子分成短语(.split(' ')),并对于每个短语,检查该短语是否存在于字典中,如果不存在,则将第一个字符大写然后,将字符串添加到字符串缓冲区。如果您当前正在处理的短语在字典中,只需将其添加到字符串缓冲区即可。

You can have a Dictionary having the words you would like to ignore, split the sentence in phrases (.split(' ')) and for each phrase, check if the phrase exists in the dictionary, if it does not, capitalize the first character and then, add the string to a string buffer. If the phrase you are currently processing is in the dictionary, simply add it to the string buffer.

别挽留 2024-10-12 01:09:23

jonnii 的答案略有改进:

var result = Regex.Replace(s.Trim(), @"\b(\w)", m => m.Value.ToUpper());
result = Regex.Replace(result, @"\s(of|in|by|and)\s", m => m.Value.ToLower(), RegexOptions.IgnoreCase);
result = result.Replace("'S", "'s");

A slight improvement on jonnii's answer:

var result = Regex.Replace(s.Trim(), @"\b(\w)", m => m.Value.ToUpper());
result = Regex.Replace(result, @"\s(of|in|by|and)\s", m => m.Value.ToLower(), RegexOptions.IgnoreCase);
result = result.Replace("'S", "'s");
山色无中 2024-10-12 01:09:22

尝试这样的操作:

public static string TitleCase(string input, params string[] dontCapitalize) {
   var split = input.Split(' ');
   for(int i = 0; i < split.Length; i++)
        split[i] = i == 0 
          ? CapitalizeWord(split[i]) 
          : dontCapitalize.Contains(split[i])
             ? split[i]
             : CapitalizeWord(split[i]);
   return string.Join(" ", split);
}
public static string CapitalizeWord(string word)
{
    return char.ToUpper(word[0]) + word.Substring(1);
}

如果您需要处理复杂的姓氏,您可以稍后更新 CapitalizeWord 方法。
将这些方法添加到类中并像这样使用它:

SomeClass.TitleCase("a test is a sentence", "is", "a"); // returns "A Test is a Sentence"

Try something like this:

public static string TitleCase(string input, params string[] dontCapitalize) {
   var split = input.Split(' ');
   for(int i = 0; i < split.Length; i++)
        split[i] = i == 0 
          ? CapitalizeWord(split[i]) 
          : dontCapitalize.Contains(split[i])
             ? split[i]
             : CapitalizeWord(split[i]);
   return string.Join(" ", split);
}
public static string CapitalizeWord(string word)
{
    return char.ToUpper(word[0]) + word.Substring(1);
}

You can then later update the CapitalizeWord method if you need to handle complex surnames.
Add those methods to a class and use it like this:

SomeClass.TitleCase("a test is a sentence", "is", "a"); // returns "A Test is a Sentence"
怼怹恏 2024-10-12 01:09:19

首先使用 ToTitleCase(),然后保留适用单词的列表,然后 Replace 回这些适用单词的全小写版本(前提是列表很小)。

适用单词的列表可以保存在字典中并非常有效地循环,用 .ToLower() 等效项替换。

Use ToTitleCase() first and then keep a list of applicable words and Replace back to the all-lower-case version of those applicable words (provided that list is small).

The list of applicable words could be kept in a dictionary and looped through pretty efficiently, replacing with the .ToLower() equivalent.

゛清羽墨安 2024-10-12 01:09:18

另一个问题的答案,如何将名称大写< /em> -

CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;

Console.WriteLine(textInfo.ToTitleCase(title));
Console.WriteLine(textInfo.ToLower(title));
Console.WriteLine(textInfo.ToUpper(title));

An answer from another question, How to Capitalize names -

CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;

Console.WriteLine(textInfo.ToTitleCase(title));
Console.WriteLine(textInfo.ToLower(title));
Console.WriteLine(textInfo.ToUpper(title));
放我走吧 2024-10-12 01:09:16

根据您计划进行大写的频率,我会采用简单的方法。您可以使用正则表达式来完成此操作,但您不希望某些单词大写这一事实使得这有点棘手。

您可以使用正则表达式通过两次传递来完成此操作:

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

此输出 Of Mice and Men isn't by CNN

第一个表达式将单词边界上的每个字母大写,第二个表达式将与列表匹配且由空格包围的所有单词小写。

这种方法的缺点是您正在使用正则表达式(现在您有两个问题)并且您需要保持排除的单词列表是最新的。我的 regex-fu 不够好,无法用一个表达式来完成它,但它可能是可能的。

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 regular expressions:

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

This outputs Of Mice and Men Isn't by CNN.

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

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.

絕版丫頭 2024-10-12 01:09:14

使用

Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase("of mice and men By CNN");

转换为正确的大小写,然后您可以按照您提到的那样循环遍历关键字。

Use

Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase("of mice and men By CNN");

to convert to proper case and then you can loop through the keywords as you have mentioned.

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