如何大写字符串中的单词
本文关键字:单词 字符串 何大写 | 更新日期: 2023-09-27 18:15:40
我有一个字符串,如web_shop_settings,并希望它为Web Shop Settings。如何在c#中实现
您可以尝试使用Linq:
string source = @"web_shop_settings";
string result = string.Concat(source.Select((c, i) => c == '_'
? ' '
: i == 0 || Char.IsWhiteSpace(source[i - 1]) || source[i - 1] == '_'
? Char.ToUpper(c)
: c));
Regex.Replace(input, @"(?:_|^)('p{L})", (match) => (match.Index > 0 ? " " : "")+match.Groups[1].Value.ToUpper())
你有答案与正则表达式,所以我想我会添加一些手动完成的参考:
public string Transform(string input)
{
var stringBuilder = new StringBuilder();
string separator = null;
foreach (var word in input.Split('_').Where(w => w.Length > 0))
{
if (separator == null)
separator = " ";
else
stringBuilder.Append(separator);
var firstLetter = word.Substring(0, 1);
stringBuilder.Append(firstLetter.ToUpper());
stringBuilder.Append(word.Substring(1));
}
return stringBuilder.ToString();
}
您可以使用以下代码片段:
public static class StringExtensions
{
public static string Capitalize(this string source, char separator)
{
return
string.Join(" ", source.Split(new char[] { separator }).Select(
c =>
string.Format("{0}{1}", c[0].ToString().ToUpper(), c.Length > 1 ? c.Substring(1) : "")));
}
}
public class Program
{
static void Main(string[] args)
{
var testString = "web_shop_settings";
Console.WriteLine(testString.Capitalize('_'));
}
}