问题描述
|
我正在尝试寻找一种有效的方法来获取输入字符串,并在每个标点符号(
. : ? !
)后的空白处加上大写字母。
输入:
\“我吃了点东西。但是我没有:
相反,没有。你怎么看?一世
别想!不好意思。moi\“
输出:
\“我吃了点东西。但是我没有:
相反,没有。你怎么看?一世
别想!不好意思。moi\“
显而易见的是将其拆分,然后大写每个组的第一个字符,然后将所有内容连接在一起。但这太丑陋了。最好的方法是什么? (我正在考虑使用大写第一个字母的MatchEvaluator
来表示Regex.Replace
,但想获得更多想法)
谢谢!
解决方法
尝试这个:
string expression = @\"[\\.\\?\\!,]\\s+([a-z])\";
string input = \"I ate something. but I didn\'t: instead,no. what do you think? i think not! excuse me.moi\";
char[] charArray = input.ToCharArray();
foreach (Match match in Regex.Matches(input,expression,RegexOptions.Singleline))
{
charArray[match.Groups[1].Index] = Char.ToUpper(charArray[match.Groups[1].Index]);
}
string output = new string(charArray);
// \"I ate something. But I didn\'t: instead,No. What do you think? I think not! Excuse me.moi\"
,快速简便:
static class Ext
{
public static string CapitalizeAfter(this string s,IEnumerable<char> chars)
{
var charsHash = new HashSet<char>(chars);
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.Length - 2; i++)
{
if (charsHash.Contains(sb[i]) && sb[i + 1] == \' \')
sb[i + 2] = char.ToUpper(sb[i + 2]);
}
return sb.ToString();
}
}
用法:
string capitalized = s.CapitalizeAfter(new[] { \'.\',\':\',\'?\',\'!\' });
,我使用扩展方法。
public static string CorrectTextCasing(this string text)
{
// /[.:?!]\\\\s[a-z]/ matches letters following a space and punctuation,// /^(?:\\\\s+)?[a-z]/ matches the first letter in a string (with optional leading spaces)
Regex regexCasing = new Regex(\"(?:[.:?!]\\\\s[a-z]|^(?:\\\\s+)?[a-z])\",RegexOptions.Multiline);
// First ensure all characters are lower case.
// (In my case it comes all in caps; this line may be omitted depending upon your needs)
text = text.ToLower();
// Capitalize each match in the regular expression,using a lambda expression
text = regexCasing.Replace(text,s => (s.Value.ToUpper));
// Return the new string.
return text;
}
然后,我可以执行以下操作:
string mangled = \"i\'m A little teapot,short AND stout. here IS my Handle.\";
string corrected = s.CorrectTextCasing();
// returns \"I\'m a little teapot,short and stout. Here is my handle.\"
,使用Regex / MatchEvaluator路线,您可以在
\"[.:?!]\\s[a-z]\"
并大写整个比赛。
,其中text变量包含字符串
string text = \"I ate something. but I didn\'t: instead,no. what do you think? i think not! excuse me.moi\";
string[] punctuators = { \"?\",\"!\",\",\"-\",\":\",\";\",\".\" };
for (int i = 0; i< 7;i++)
{
int pos = text.IndexOf(punctuators[i]);
while(pos!=-1)
{
text = text.Insert(pos+2,char.ToUpper(text[pos + 2]).ToString());
text = text.Remove(pos + 3,1);
pos = text.IndexOf(punctuators[i],pos+1);
}
}