我有很多字符串.每个字符串前面至少有1个$
.循环遍历每个字符串的字符以计算每个字符串的数量的最佳方法是什么$
.
例如:
"$hello" - 1
"$$hello" - 2
"$$h$ello" - 2
Run Code Online (Sandbox Code Playgroud)
gpr*_*ant 75
您可以使用Count方法
var count = mystring.Count(x => x == '$')
Run Code Online (Sandbox Code Playgroud)
Yur*_*ich 34
int count = myString.TakeWhile(c => c == '$').Count();
Run Code Online (Sandbox Code Playgroud)
没有LINQ
int count = 0;
while(count < myString.Length && myString[count] == '$') count++;
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 18
最简单的方法是使用LINQ:
var count = text.TakeWhile(c => c == '$').Count();
Run Code Online (Sandbox Code Playgroud)
肯定有更有效的方法,但这可能是最简单的方法.
你可以这样做,它不需要LINQ,但它不是最好的方法(因为你将整个字符串拆分并放在一个数组中,只需选择它的长度,你最好只做一个while
循环并检查每个字符),但它的工作原理.
int count = test.Split('$').Length - 1;
Run Code Online (Sandbox Code Playgroud)
int count = yourText.Length - yourText.TrimStart('$').Length;
Run Code Online (Sandbox Code Playgroud)
小智 6
var str ="hello";
str.Where(c => c == 'l').Count() // 2
Run Code Online (Sandbox Code Playgroud)
小智 5
int count = Regex.Matches(myString,"$").Count;
Run Code Online (Sandbox Code Playgroud)
public static int GetHowManyTimeOccurenceCharInString(string text, char c)
{
int count = 0;
foreach(char ch in text)
{
if(ch.Equals(c))
{
count++;
}
}
return count;
}
Run Code Online (Sandbox Code Playgroud)