Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何计算某个特定字符在其他特定字符第一次出现之前出现的频率?_C#_String_Char - Fatal编程技术网

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');