C# 如何计算某个特定字符在其他特定字符第一次出现之前出现的频率?
我有一个C# 如何计算某个特定字符在其他特定字符第一次出现之前出现的频率?,c#,string,char,C#,String,Char,我有一个字符串像asdafahxlkax 如何计算在第一个x出现之前a出现3次 谢谢。试试: public int CountBeforeChar(char toCount, char beforeChar, string testString) { // Handle situation where we cannot find beforeChar in testString var idx = testString.IndexOf(beforeChar); idx = idx
字符串
像asdafahxlkax
如何计算在第一个x
出现之前a
出现3次
谢谢。试试:
public int CountBeforeChar(char toCount, char beforeChar, string testString)
{
// Handle situation where we cannot find beforeChar in testString
var idx = testString.IndexOf(beforeChar);
idx = idx == -1 ? testString.Length - 1 : idx;
return testString
// Take substring until first occurence of "beforeChar"
.Substring(0, idx)
// Count all occurences of desired character in that substring
.Count(ch => ch == toCount);
}
String str=“asdafahxlkax”;
char[]chars=str.ToCharArray();
int计数器=0;
for(int i=0;i
当x包含0次时,您需要定义是否希望此操作失败。但总的来说,这是一个简单的方法 最简单的解决方案是将字符串除以另一个字符,并计算第一部分中目标字符的出现次数:
string str = "asdafahxlkax";
int count = 0;
if (str.Contains('x'))
count = str.Split('x').First().Count(c => c == 'a');
else
count = str.Count(c => c == 'a');
更新:
更干净有效的解决方案是使用TakeWhile
获取“x”之前的部分字符串(如果存在,或者它将获取整个字符串),并计算目标字符的出现次数(信用证:@mjwills):
利用您的想象力,尝试使用String.Substring()和String.IndexOf()
var result=“asdafahxlkax”.TakeWhile(z=>z!=“x”).Count(z=>z==“a”)代码>逐字符循环,在找到a
时增加计数。找到x
时退出循环。我喜欢这样。不确定在x
之前的5次“a”是否也有效,或者当x不是字符串的一部分,而是a等时会发生什么情况。只是一个提示:不需要调用tocharray
或chars
变量。string
类实现了IEnumerable
,因此您可以直接循环字符串的字符。这可能被简化为var count=str.Split('x').First().count(c=>c='a')代码>注意-它几乎肯定会比以前的TakeWhile
解决方案慢(因为您多次迭代字符串,分配新字符串等)。@mjwills字符串中可能没有“x”,因此我尝试使解决方案通过所有测试用例,我同意,TakeWhile
将是更干净、更高效的选择。
string str = "asdafahxlkax";
int count = 0;
if (str.Contains('x'))
count = str.Split('x').First().Count(c => c == 'a');
else
count = str.Count(c => c == 'a');
int count = str.TakeWhile(c => c != 'x').Count(c => c == 'a');