英文:
Convert Any Sting To A Specific Format
问题
我正在尝试将一种字符串转换为驼峰命名法。这是字符串:
here %it -RAINS
期望的输出:
hereItRains
我尝试了以下代码:
public static string ToCamelCase(this string str)
{
var words = str.Split(new[] { "_", "-", "%" }, StringSplitOptions.RemoveEmptyEntries);
words = words.Select(word => char.ToUpper(word[0]) + word.Substring(1)).ToArray();
return string.Join(string.Empty, words);
}
得到的输出如下:
Here It RAINS
这里有什么我错过的地方吗?这是我迄今为止尝试的链接 - CamelCase
英文:
I am trying to convert a type of string into camel case. Here's the string:
here %it -RAINS
Expected Output:
hereItRains
I tried the following:
public static string ToCamelCase(this string str)
{
var words = str.Split(new[] { "_", "-", "%" }, StringSplitOptions.RemoveEmptyEntries);
words = words.Select(word => char.ToUpper(word[0]) + word.Substring(1)).ToArray();
return string.Join(string.Empty, words);
}
Got the output as below:
Here It RAINS
Is there anything that I missed here? Here's the link that I tried so far - CamelCase
答案1
得分: 3
你已经有很多答案了,但我想再添加一个新的答案,使用原始的 C# 代码来处理字符串,避免一些内存分配并减少处理时间。
public static string ToCamelCase(this string value)
{
if (string.IsNullOrWhiteSpace(value))
return value;
var upperCase = false;
var sb = new StringBuilder();
for (int i = 0; i < value.Length; i++)
{
if (char.IsWhiteSpace(value[i]) || char.IsPunctuation(value[i]))
{
upperCase = true;
continue;
}
char ch;
if (upperCase)
{
ch = char.ToUpperInvariant(value[i]);
}
else
{
ch = char.IsLower(value[i]) ? value[i] : char.ToLowerInvariant(value[i]);
}
upperCase = false;
sb.Append(ch);
}
return sb.ToString();
}
当我们使用像 ToArray、Split、ToLower、Regex 等方法时,会在内存中创建许多对象,通过一些逻辑可以避免这种情况。
基准测试
英文:
You already have many answers here, but I would like to add a new one, which is using raw C# code to process the string, avoid some memory allocation and reduce processing time.
public static string ToCamelCase(this string value)
{
if (string.IsNullOrWhiteSpace(value))
return value;
var upperCase = false;
var sb = new StringBuilder();
for (int i = 0; i < value.Length; i++)
{
if (char.IsWhiteSpace(value[i]) || char.IsPunctuation(value[i]))
{
upperCase = true;
continue;
}
char ch;
if (upperCase)
{
ch = char.ToUpperInvariant(value[i]);
}
else
{
ch = char.IsLower(value[i]) ? value[i] : char.ToLowerInvariant(value[i]);
}
upperCase = false;
sb.Append(ch);
}
return sb.ToString();
}
When we use methods like ToArray, Split, ToLower, Regex, etc, we are creating many objects in memory and this can be avoided with some logic.
Benchmark tests
答案2
得分: 2
我建议使用正则表达式来匹配所有需要转换为小写(第一个单词)或标题大小写(其余单词)的单词:
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
...
public static string ToCamelCase(string value) {
if (string.IsNullOrEmpty(value))
return value;
return string.Concat(Regex
.Matches(value, @"\p{L}+")
.Select(match => match.Value.ToLower(CultureInfo.InvariantCulture))
.Select((word, index) => index == 0
? word
: CultureInfo.InvariantCulture.TextInfo.ToTitleCase(word)));
}
备注:
\p{L}+
模式代表“一个或多个Unicode字母”。ToTitleCase
将任何单词转换为标题大小写,除了全大写的单词(被视为首字母缩写词而不进行更改),这就是为什么我对任何单词调用ToLower()
的原因。
英文:
I suggest using regular expressions in order to match all the words which we should turn into lower case (the very first word) or title case (all the rest words):
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
...
public static string ToCamelCase(string value) {
if (string.IsNullOrEmpty(value))
return value;
return string.Concat(Regex
.Matches(value, @"\p{L}+")
.Select(match => match.Value.ToLower(CultureInfo.InvariantCulture))
.Select((word, index) => index == 0
? word
: CultureInfo.InvariantCulture.TextInfo.ToTitleCase(word)));
}
Remarks:
\p{L}+
pattern stands for "one or more Unicode letters".ToTitleCase
turns any word into title case except all capital letters words (which are treated as acronyms and not changed), that's why I callToLower()
for any word.
答案3
得分: 1
我为我的大学作业编写了以下代码,并且它完美地运行了。ToCamelCase
函数接受一个输入文本,使用空格、下划线和连字符作为分隔符,将其分解为单词,然后将每个单词转换为标题大小写(将首字母大写),除了第一个单词。TextInfo
类根据当前的区域设置处理正确的大小写。
class Program
{
static string ToCamelCase(string input)
{
TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
string[] words = input.Split(new[] { ' ', '_', '-' }, StringSplitOptions.RemoveEmptyEntries);
if (words.Length == 0)
return input;
string camelCase = words[0].ToLower();
for (int i = 1; i < words.Length; i++)
{
camelCase += textInfo.ToTitleCase(words[i].ToLower());
}
return camelCase;
}
static void Main(string[] args)
{
string input = "convert_this_string_to_camel_case";
string camelCaseOutput = ToCamelCase(input);
Console.WriteLine(camelCaseOutput);
}
}
英文:
I did the following code for one of my college assignment and it worked perfectly fine. The ToCamelCase
function takes an input text, breaks it into words using spaces, underscores, and hyphens as delimiters, and then transforms each word to title case (capitalising the initial letter) except the first. The TextInfo
class handles correct case depending on current culture.
class Program
{
static string ToCamelCase(string input)
{
TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
string[] words = input.Split(new[] { ' ', '_', '-' }, StringSplitOptions.RemoveEmptyEntries);
if (words.Length == 0)
return input;
string camelCase = words[0].ToLower();
for (int i = 1; i < words.Length; i++)
{
camelCase += textInfo.ToTitleCase(words[i].ToLower());
}
return camelCase;
}
static void Main(string[] args)
{
string input = "convert_this_string_to_camel_case";
string camelCaseOutput = ToCamelCase(input);
Console.WriteLine(camelCaseOutput);
}
}
答案4
得分: 1
请注意,我将为您翻译以下内容:
编辑ToCamelCase
函数如下:
public string ToCamelCase(string str)
{
var allWords = str.Split(new[] { "_", "-", "%", " " }, StringSplitOptions.RemoveEmptyEntries).ToList();
var words = allWords.Skip(1).Select(word => char.ToUpper(word[0]) + word.Substring(1).ToLower()).ToList();
words.Insert(0, allWords[0]);
return string.Join(string.Empty, words);
}
-
将
" "
添加到您的Split集合中。 -
在
word.Substring(1)
后添加.ToLower()
。 -
使用
allWords.Skip(1)
跳过第一个单词。
结果:
a b c %d ==> aBCD
here %it -RAINS ==> hereItRains
请注意,这是对代码进行的修改和结果示例。
英文:
Edit the ToCamelCase
function as follows:
public string ToCamelCase(string str)
{
var allWords = str.Split(new[] { "_", "-", "%", " " }, StringSplitOptions.RemoveEmptyEntries).ToList();
var words = allWords.Skip(1).Select(word => char.ToUpper(word[0]) + word.Substring(1).ToLower()).ToList();
words.Insert(0, allWords[0]);
return string.Join(string.Empty, words);
}
-
add
" "
to your Split collection. -
add
.ToLower()
to word.Substring(1) -
skip the first word with
allWords.Skip(1)
result:
a b c %d ==> aBCD
here %it -RAINS ==> hereItRains
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论