C# 将 Pascal Case 转换为句子的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/323314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to convert Pascal Case to a sentence
提问by Garry Shutler
What is the best way to convert from Pascal Case (upper Camel Case) to a sentence.
从 Pascal Case(上 Camel Case)转换为句子的最佳方法是什么。
For example starting with
例如从
"AwaitingFeedback"
and converting that to
并将其转换为
"Awaiting feedback"
C# preferable but I could convert it from Java or similar.
C# 更可取,但我可以从 Java 或类似版本转换它。
回答by schnaader
Pseudo-code:
伪代码:
NewString = "";
Loop through every char of the string (skip the first one)
If char is upper-case ('A'-'Z')
NewString = NewString + ' ' + lowercase(char)
Else
NewString = NewString + char
Better ways can perhaps be done by using regex or by string replacement routines (replace 'X' with ' x')
更好的方法也许可以通过使用正则表达式或字符串替换例程来完成(将 'X' 替换为 'x')
回答by Antoine
I'd use a regex, inserting a space before each upper case character, then lowering all the string.
我会使用正则表达式,在每个大写字符之前插入一个空格,然后降低所有字符串。
string spacedString = System.Text.RegularExpressions.Regex.Replace(yourString, "\B([A-Z])", " \k");
spacedString = spacedString.ToLower();
回答by Autodidact
Here you go...
干得好...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CamelCaseToString
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(CamelCaseToString("ThisIsYourMasterCallingYou"));
}
private static string CamelCaseToString(string str)
{
if (str == null || str.Length == 0)
return null;
StringBuilder retVal = new StringBuilder(32);
retVal.Append(char.ToUpper(str[0]));
for (int i = 1; i < str.Length; i++ )
{
if (char.IsLower(str[i]))
{
retVal.Append(str[i]);
}
else
{
retVal.Append(" ");
retVal.Append(char.ToLower(str[i]));
}
}
return retVal.ToString();
}
}
}
回答by PhiLho
It is easy to do in JavaScript (or PHP, etc.) where you can define a function in the replace call:
在 JavaScript(或 PHP 等)中很容易做到,您可以在替换调用中定义一个函数:
var camel = "AwaitingFeedbackDearMaster";
var sentence = camel.replace(/([A-Z].)/g, function (c) { return ' ' + c.toLowerCase(); });
alert(sentence);
Although I haven't solved the initial cap problem... :-)
虽然我还没有解决最初的上限问题... :-)
Now, for the Java solution:
现在,对于 Java 解决方案:
String ToSentence(String camel)
{
if (camel == null) return ""; // Or null...
String[] words = camel.split("(?=[A-Z])");
if (words == null) return "";
if (words.length == 1) return words[0];
StringBuilder sentence = new StringBuilder(camel.length());
if (words[0].length() > 0) // Just in case of camelCase instead of CamelCase
{
sentence.append(words[0] + " " + words[1].toLowerCase());
}
else
{
sentence.append(words[1]);
}
for (int i = 2; i < words.length; i++)
{
sentence.append(" " + words[i].toLowerCase());
}
return sentence.toString();
}
System.out.println(ToSentence("AwaitingAFeedbackDearMaster"));
System.out.println(ToSentence(null));
System.out.println(ToSentence(""));
System.out.println(ToSentence("A"));
System.out.println(ToSentence("Aaagh!"));
System.out.println(ToSentence("stackoverflow"));
System.out.println(ToSentence("disableGPS"));
System.out.println(ToSentence("Ahh89Boo"));
System.out.println(ToSentence("ABC"));
Note the trick to split the sentence without loosing any character...
注意在不丢失任何字符的情况下拆分句子的技巧......
回答by Garry Shutler
Here's a basic way of doing it that I came up with using Regex
这是我想出的使用 Regex 的基本方法
public static string CamelCaseToSentence(this string value)
{
var sb = new StringBuilder();
var firstWord = true;
foreach (var match in Regex.Matches(value, "([A-Z][a-z]+)|[0-9]+"))
{
if (firstWord)
{
sb.Append(match.ToString());
firstWord = false;
}
else
{
sb.Append(" ");
sb.Append(match.ToString().ToLower());
}
}
return sb.ToString();
}
It will also split off numbers which I didn't specify but would be useful.
它还会拆分我没有指定但会很有用的数字。
回答by Andrew Bullock
string camel = "MyCamelCaseString";
string s = Regex.Replace(camel, "([A-Z])", " ").ToLower().Trim();
Console.WriteLine(s.Substring(0,1).ToUpper() + s.Substring(1));
Edit: didn't notice your casing requirements, modifed accordingly. You could use a matchevaluator to do the casing, but I think a substring is easier. You could also wrap it in a 2nd regex replace where you change the first character
编辑:没有注意到您的外壳要求,进行了相应的修改。您可以使用 matchevaluator 进行大小写,但我认为子字符串更容易。您也可以将它包装在第二个正则表达式替换中,您可以在其中更改第一个字符
"^\w"
to upper
到上
\U (i think)
回答by Binary Worrier
Mostly already answered here
大多数已经在这里回答
Small chage to the accepted answer, to convert the second and subsequent Capitalised letters to lower case, so change
对已接受答案的小改动,将第二个和后续大写字母转换为小写,因此更改
if (char.IsUpper(text[i]))
newText.Append(' ');
newText.Append(text[i]);
to
到
if (char.IsUpper(text[i]))
{
newText.Append(' ');
newText.Append(char.ToLower(text[i]));
}
else
newText.Append(text[i]);
回答by Binary Worrier
public static string ToSentenceCase(this string str)
{
return Regex.Replace(str, "[a-z][A-Z]", m => m.Value[0] + " " + char.ToLower(m.Value[1]));
}
In versions of visual studio after 2015, you can do
在2015年以后的visual studio版本中,你可以做
public static string ToSentenceCase(this string str)
{
return Regex.Replace(str, "[a-z][A-Z]", m => $"{m.Value[0]} {char.ToLower(m.Value[1])}");
}
Based on: Converting Pascal case to sentences using regular expression
回答by Fraser
An xquery solution that works for both UpperCamel and lowerCamel case:
适用于 UpperCamel 和 lowerCamel 案例的 xquery 解决方案:
To output sentence case (only the first character of the first word is capitalized):
输出句子大小写(仅第一个单词的第一个字符大写):
declare function content:sentenceCase($string)
{
let $firstCharacter := substring($string, 1, 1)
let $remainingCharacters := substring-after($string, $firstCharacter)
return
concat(upper-case($firstCharacter),lower-case(replace($remainingCharacters, '([A-Z])', ' ')))
};
To output title case (first character of each word capitalized):
输出标题大小写(每个单词的第一个字符大写):
declare function content:titleCase($string)
{
let $firstCharacter := substring($string, 1, 1)
let $remainingCharacters := substring-after($string, $firstCharacter)
return
concat(upper-case($firstCharacter),replace($remainingCharacters, '([A-Z])', ' '))
};
回答by SSTA
This works for me:
这对我有用:
Regex.Replace(strIn, "([A-Z]{1,2}|[0-9]+)", " ").TrimStart()