gpt4 book ai didi

c# - 将字符串转换为首字母大写

转载 作者:太空狗 更新时间:2023-10-29 23:07:31 25 4
gpt4 key购买 nike

我需要将以下内容转换为标题大小写:

  1. 短语中的第一个单词;

  2. 其他词,在同一个词组中,长度大于minLength。

我在看 ToTitleCase但结果不是预期的。

所以当 minLength = 2 时,短语“the car is very fast”将变成“The Car is Very快”。

我能够使用以下方法将第一个单词变成大写:

Char[] letters = source.ToCharArray();
letters[0] = Char.ToUpper(letters[0]);

为了得到我正在使用的词:

Regex.Matches(source, @"\b(\w|['-])+\b"

但我不确定如何将所有这些放在一起

谢谢你,米格尔

最佳答案

示例代码:

string input = "i have the car which is very fast";
int minLength = 2;
string regexPattern = string.Format(@"^\w|\b\w(?=\w{{{0}}})", minLength);
string output = Regex.Replace(input, regexPattern, m => m.Value.ToUpperInvariant());

更新(针对单个字符串中有多个句子的情况)。

string input = "i have the car which is very fast. me is slow.";
int minLength = 2;
string regexPattern = string.Format(@"(?<=(^|\.)\s*)\w|\b\w(?=\w{{{0}}})", minLength);
string output = Regex.Replace(input, regexPattern, m => m.Value.ToUpperInvariant());

输出:

I Have The Car Which is Very Fast. Me is Slow.

您可能希望处理!?等符号,那么您可以使用下面的代码。您可以根据需要添加任意数量的句子终止符号。

string input = "i have the car which is very fast! me is slow.";
int minLength = 2;
string regexPattern = string.Format(@"(?<=(^|[.!?])\s*)\w|\b\w(?=\w{{{0}}})", minLength);
string output = Regex.Replace(input, regexPattern, m => m.Value.ToUpperInvariant());

更新 (2) - 将 e-marketing 转换为 E-Marketing(将 - 视为有效词符号):

string input = "i have the car which is very fast! me is slow. it is very nice to learn e-marketing these days.";
int minLength = 2;
string regexPattern = string.Format(@"(?<=(^|[.!?])\s*)\w|\b\w(?=[-\w]{{{0}}})", minLength);
string output = Regex.Replace(input, regexPattern, m => m.Value.ToUpperInvariant());

关于c# - 将字符串转换为首字母大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23860116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com