我有字符串,例如:
1.1
1.11
11.11
1.1.1
11.11.11
所有这些都是单个字符串,没有空格,只有数字和句点。
我需要能够计算字符串中的句点数。有没有一种简单的方法可以在 C# 中做到这一点?
我有字符串,例如:
1.1
1.11
11.11
1.1.1
11.11.11
所有这些都是单个字符串,没有空格,只有数字和句点。
我需要能够计算字符串中的句点数。有没有一种简单的方法可以在 C# 中做到这一点?
有几种方法,例如(需要框架 3.5 或更高版本):
int cnt = str.Count(c => c == '.');
或者:
int cnt = 0;
foreach (char c in str) if (c == '.') cnt++;
或者:
int cnt = str.Length - str.Replace(".", "").Length;
当我输入你的确切问题时,谷歌上的第一个结果......
做一些研究...
int count = 0;
string st = "Hi, these pretzels are making me thirsty; drink this tea. Run like heck. It's a good day.";
foreach(char c in st) {
if(char.IsLetter(c)) {
count++;
}
}
lblResult.Text = count.ToString();
记住字符串是字符数组。
您可以在 linq 查询中使用Enumerable.Count
"11.11.11".Count(c => c=='.'); // 2
"1.1.1.1".Count(c => c=='.'); // 3
string stringToTest = "1.11";
string[] split = stringToTest.Split('.');
int count = split.Length - 1;
Console.WriteLine("Your string has {0} periods in it", count);