我想将字符串中每个句子的第一个字母大写。 我有一个字符串,例如。 “你好吗? 我很好,你呢? 我很好。好天气!”
而且我想把里面每个句子的第一个字母大写。所以, “你好吗? 我没事,你呢?” 等
编辑:到目前为止,我刚刚尝试过
public static string FirstCharToUpper(string input)
{
if (String.IsNullOrEmpty(input))
throw new ArgumentException("ARGH!");
return input.First().ToString().ToUpper() + input.Substring(1);
}
但这会将每个单词中的第一个字母大写,而不是句子:/
最佳答案
我建议使用简单的方法,遍历字符串。
您也可以将其作为字符串
的扩展。
public static class StringExtension
{
public static string CapitalizeFirst(this string s)
{
bool IsNewSentense = true;
var result = new StringBuilder(s.Length);
for (int i = 0; i < s.Length; i++)
{
if (IsNewSentense && char.IsLetter(s[i]))
{
result.Append (char.ToUpper (s[i]));
IsNewSentense = false;
}
else
result.Append (s[i]);
if (s[i] == '!' || s[i] == '?' || s[i] == '.')
{
IsNewSentense = true;
}
}
return result.ToString();
}
}
所以,你可以按照下面的方式使用它
string str = "hello, how are you? i'm fine, you? i'm good. nice weather!".CapitalizeFirst();
所以 str
等于
Hello, how are you? I'm fine, you? I'm good. Nice weather!
关于C# 将字符串中每个句子的第一个字母大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36089495/