我想将字符串中每个句子的第一个字母大写.我有一个字符串,例如."你好,你好吗?我很好,你呢?我很好.天气很好!"
我想把每个句子的第一个字母大写.所以,"你好,你好吗?我很好,你呢?" 等等
编辑:到目前为止,我刚试过
public static string FirstCharToUpper(string input)
{
if (String.IsNullOrEmpty(input))
throw new ArgumentException("ARGH!");
return input.First().ToString().ToUpper() + input.Substring(1);
}
Run Code Online (Sandbox Code Playgroud)
但这会使每个单词中的第一个字母大写,而不是句子:/
我建议简单的方法,迭代字符串.
你也可以把它作为一个扩展string.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
所以,您可以按照以下方式使用它
string str = "hello, how are you? i'm fine, you? i'm good. nice weather!".CapitalizeFirst();
Run Code Online (Sandbox Code Playgroud)
所以str等于
你好,你好吗?我很好,你呢?我很好.好天气!
| 归档时间: |
|
| 查看次数: |
4752 次 |
| 最近记录: |